|
|
@ -22,7 +22,7 @@ public class TreeNode {
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
/**
|
|
|
|
* Generate a binary tree with an array
|
|
|
|
* Generate a binary tree given an array
|
|
|
|
* @param arr
|
|
|
|
* @param arr
|
|
|
|
* @return
|
|
|
|
* @return
|
|
|
|
*/
|
|
|
|
*/
|
|
|
@ -32,19 +32,19 @@ public class TreeNode {
|
|
|
|
|
|
|
|
|
|
|
|
TreeNode root = new TreeNode(arr[0]);
|
|
|
|
TreeNode root = new TreeNode(arr[0]);
|
|
|
|
Queue<TreeNode> queue = new LinkedList<>() {{ add(root); }};
|
|
|
|
Queue<TreeNode> queue = new LinkedList<>() {{ add(root); }};
|
|
|
|
int i = 1;
|
|
|
|
int i = 0;
|
|
|
|
while(!queue.isEmpty()) {
|
|
|
|
while(!queue.isEmpty()) {
|
|
|
|
TreeNode node = queue.poll();
|
|
|
|
TreeNode node = queue.poll();
|
|
|
|
|
|
|
|
if (++i >= arr.length) break;
|
|
|
|
if(arr[i] != null) {
|
|
|
|
if(arr[i] != null) {
|
|
|
|
node.left = new TreeNode(arr[i]);
|
|
|
|
node.left = new TreeNode(arr[i]);
|
|
|
|
queue.add(node.left);
|
|
|
|
queue.add(node.left);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
i++;
|
|
|
|
if (++i >= arr.length) break;
|
|
|
|
if(arr[i] != null) {
|
|
|
|
if(arr[i] != null) {
|
|
|
|
node.right = new TreeNode(arr[i]);
|
|
|
|
node.right = new TreeNode(arr[i]);
|
|
|
|
queue.add(node.right);
|
|
|
|
queue.add(node.right);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
i++;
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return root;
|
|
|
|
return root;
|
|
|
|
}
|
|
|
|
}
|
|
|
@ -71,20 +71,4 @@ public class TreeNode {
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return list;
|
|
|
|
return list;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
|
|
* Get a tree node with specific value in a binary tree
|
|
|
|
|
|
|
|
* @param root
|
|
|
|
|
|
|
|
* @param val
|
|
|
|
|
|
|
|
* @return
|
|
|
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
public static TreeNode getTreeNode(TreeNode root, int val) {
|
|
|
|
|
|
|
|
if (root == null)
|
|
|
|
|
|
|
|
return null;
|
|
|
|
|
|
|
|
if (root.val == val)
|
|
|
|
|
|
|
|
return root;
|
|
|
|
|
|
|
|
TreeNode left = getTreeNode(root.left, val);
|
|
|
|
|
|
|
|
TreeNode right = getTreeNode(root.right, val);
|
|
|
|
|
|
|
|
return left != null ? left : right;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|