Construct Binary Tree from Preorder and Inorder Traversal, Construct Binary Tree from Inorder and Postorder Traversal, Binary Tree Inorder Traversal, Convert Sorted Array to Binary Search Tree, Convert Sorted List to Binary Search Tree, Flatten Binary Tree to Linked List
private TreeNode helper(int[] inorder, int[] postorder, int l, int r){
if(l>r) returnnull;
int cur=postorder[pos];
TreeNode tmp=new TreeNode(cur);
pos--;
int i=l;
for(;i<=r;i++){
if(inorder[i]==cur) break;
}
tmp.right=helper(inorder,postorder, i+1, r);
tmp.left=helper(inorder, postorder, l, i-1);
return tmp;
}
Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes’ values. For example: Given binary tree {1,#,2,3},
1
2
3
4
5
1
\
2
/
3
return [1,3,2]. Note: Recursive solution is trivial, could you do it iteratively? confused what “{1,#,2,3}” means? > read more on how binary tree is serialized on OJ.
Recursive Method(Trivial)
1
2
3
4
5
6
7
8
9
10
11
12
13
public ArrayList<Integer> inorderTraversal(TreeNode root) {
Given a binary tree, flatten it to a linked list in-place. For example, Given
1
2
3
4
5
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
2
3
4
5
6
7
8
9
10
11
1
\
2
\
3
\
4
\
5
\
6
Iterative Solution
Using a stack to solve this problem is easy: start from root, push right, left into stack. If stack is not empty, set cur.right to stack.peek(). Continue to process the next node from top of stack. But to do it inplace requires to keep track of the origin right node. Overall process is to squeeze the left node into between its parents and right child.