mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-23 09:42:28 +08:00
Format the Java codes with the Reat Hat extension.
This commit is contained in:
@ -8,40 +8,36 @@ package include;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Definition for a binary tree node.
|
||||
*/
|
||||
/* Definition for a binary tree node. */
|
||||
public class TreeNode {
|
||||
public int val; // 节点值
|
||||
public int height; // 节点高度
|
||||
public TreeNode left; // 左子节点引用
|
||||
public int val; // 节点值
|
||||
public int height; // 节点高度
|
||||
public TreeNode left; // 左子节点引用
|
||||
public TreeNode right; // 右子节点引用
|
||||
|
||||
public TreeNode(int x) {
|
||||
val = x;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a binary tree given an array
|
||||
* @param list
|
||||
* @return
|
||||
*/
|
||||
/* Generate a binary tree given an array */
|
||||
public static TreeNode listToTree(List<Integer> list) {
|
||||
int size = list.size();
|
||||
if (size == 0)
|
||||
return null;
|
||||
|
||||
|
||||
TreeNode root = new TreeNode(list.get(0));
|
||||
Queue<TreeNode> queue = new LinkedList<>() {{ add(root); }};
|
||||
int i = 0;
|
||||
while(!queue.isEmpty()) {
|
||||
while (!queue.isEmpty()) {
|
||||
TreeNode node = queue.poll();
|
||||
if (++i >= size) break;
|
||||
if (++i >= size)
|
||||
break;
|
||||
if (list.get(i) != null) {
|
||||
node.left = new TreeNode(list.get(i));
|
||||
queue.add(node.left);
|
||||
}
|
||||
if (++i >= size) break;
|
||||
if (++i >= size)
|
||||
break;
|
||||
if (list.get(i) != null) {
|
||||
node.right = new TreeNode(list.get(i));
|
||||
queue.add(node.right);
|
||||
@ -50,23 +46,19 @@ public class TreeNode {
|
||||
return root;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize a binary tree to a list
|
||||
* @param root
|
||||
* @return
|
||||
*/
|
||||
/* Serialize a binary tree to a list */
|
||||
public static List<Integer> treeToList(TreeNode root) {
|
||||
List<Integer> list = new ArrayList<>();
|
||||
if(root == null) return list;
|
||||
if (root == null)
|
||||
return list;
|
||||
Queue<TreeNode> queue = new LinkedList<>() {{ add(root); }};
|
||||
while(!queue.isEmpty()) {
|
||||
while (!queue.isEmpty()) {
|
||||
TreeNode node = queue.poll();
|
||||
if(node != null) {
|
||||
if (node != null) {
|
||||
list.add(node.val);
|
||||
queue.add(node.left);
|
||||
queue.add(node.right);
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
list.add(null);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user