mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-22 15:53:50 +08:00
Optimize arrToTree function
in java, cpp, py, go, js, ts.
This commit is contained in:
@ -8,6 +8,7 @@ package include;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
|
||||
class Trunk {
|
||||
Trunk prev;
|
||||
String str;
|
||||
@ -103,4 +104,11 @@ public class PrintUtil {
|
||||
System.out.println(kv.getKey() + " -> " + kv.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static void printHeap(PriorityQueue<Integer> queue) {
|
||||
Integer[] nums = (Integer[])queue.toArray();
|
||||
TreeNode root = TreeNode.arrToTree(nums);
|
||||
|
||||
printTree(root);
|
||||
}
|
||||
}
|
||||
|
@ -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