How to construct a binary tree from a sequence of values.
Input: [4,9,0,5,1]
4
/ \
9 0
/ \
5 1
Input with null: [1,2,3,null,5,6,7]
1
/ \
2 3
/ \ / \
null 5 6 7
Note: the tree is not a binary search tree. The nodes are inserted in pre order ( root, left, right ). Start by filling the child nodes from left to right. Once the level is filled, go to the next level. My intuition is to keep reference of the parent nodes.
public class TreeNode {
public int value;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) {
value = x;
}
}
public static TreeNode createTree(List<Integer> values) {
// ???
// return the root node
}
I feel a stupid asking this.
PS: I wondered how the tree was built from the inputs https://leetcode.com/problems/sum-root-to-leaf-numbers/
PS2 : Berto99 gave a draft of recursive way. Wondering about the iterative way (which will need to keep references of parent nodes)
nullvalue toint value?