hello-algo/codes/java/include/TreeNode.java

75 lines
1.9 KiB
Java
Raw Normal View History

/**
* File: TreeNode.java
* Created Time: 2022-11-25
* Author: Krahets (krahets@163.com)
*/
2022-11-08 02:58:42 +08:00
package include;
import java.util.*;
/**
* Definition for a binary tree node.
*/
public class TreeNode {
2022-12-10 20:46:47 +08:00
public int val; // 结点值
public int height; // 结点高度
public TreeNode left; // 左子结点引用
public TreeNode right; // 右子结点引用
2022-11-08 02:58:42 +08:00
public TreeNode(int x) {
val = x;
}
/**
* Generate a binary tree given an array
2022-11-08 02:58:42 +08:00
* @param arr
* @return
*/
public static TreeNode arrToTree(Integer[] arr) {
2022-12-02 00:53:19 +08:00
if (arr.length == 0)
return null;
2022-11-08 02:58:42 +08:00
TreeNode root = new TreeNode(arr[0]);
Queue<TreeNode> queue = new LinkedList<>() {{ add(root); }};
int i = 0;
2022-11-08 02:58:42 +08:00
while(!queue.isEmpty()) {
TreeNode node = queue.poll();
if (++i >= arr.length) break;
2022-11-08 02:58:42 +08:00
if(arr[i] != null) {
node.left = new TreeNode(arr[i]);
queue.add(node.left);
}
if (++i >= arr.length) break;
2022-11-08 02:58:42 +08:00
if(arr[i] != null) {
node.right = new TreeNode(arr[i]);
queue.add(node.right);
}
}
return root;
}
/**
* Serialize a binary tree to a list
* @param root
* @return
*/
public static List<Integer> treeToList(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root == null) return list;
Queue<TreeNode> queue = new LinkedList<>() {{ add(root); }};
while(!queue.isEmpty()) {
TreeNode node = queue.poll();
if(node != null) {
list.add(node.val);
queue.add(node.left);
queue.add(node.right);
}
else {
list.add(null);
}
}
return list;
}
}