mirror of
https://github.com/krahets/hello-algo.git
synced 2025-12-16 03:59:18 +08:00
Optimize arrToTree function
in java, cpp, py, go, js, ts.
This commit is contained in:
@@ -22,7 +22,7 @@ public class TreeNode {
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a binary tree with an array
|
||||
* Generate a binary tree given an array
|
||||
* @param arr
|
||||
* @return
|
||||
*/
|
||||
@@ -32,19 +32,19 @@ public class TreeNode {
|
||||
|
||||
TreeNode root = new TreeNode(arr[0]);
|
||||
Queue<TreeNode> queue = new LinkedList<>() {{ add(root); }};
|
||||
int i = 1;
|
||||
int i = 0;
|
||||
while(!queue.isEmpty()) {
|
||||
TreeNode node = queue.poll();
|
||||
if (++i >= arr.length) break;
|
||||
if(arr[i] != null) {
|
||||
node.left = new TreeNode(arr[i]);
|
||||
queue.add(node.left);
|
||||
}
|
||||
i++;
|
||||
if (++i >= arr.length) break;
|
||||
if(arr[i] != null) {
|
||||
node.right = new TreeNode(arr[i]);
|
||||
queue.add(node.right);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return root;
|
||||
}
|
||||
@@ -71,20 +71,4 @@ public class TreeNode {
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user