Optimize arrToTree function

in java, cpp, py, go, js, ts.
This commit is contained in:
Yudong Jin
2023-01-08 19:03:22 +08:00
parent c411969bd1
commit dcc3b2e35b
29 changed files with 222 additions and 114 deletions

View File

@ -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);
}
}

View File

@ -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;
}
}