Tree
Tree
1. Traversal
(1) Preorder Traversal
// Iterative version
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode curNode = stack.pop();
res.add(curNode.val);
if (curNode.right != null) {
stack.push(curNode.right);
}
if (curNode.left != null) {
stack.push(curNode.left);
}
}
return res;
}(2) Inorder Traversal
(3) Postorder Traversal
2. DFS and BFS in Tree
(1) BFS
This is essentially Binary Tree Level Order Traversal
(2) DFS
DFS is helpful to get the size of subtree: Largest BST Subtree
DFS is helpful to get the height of subtree: Balanced Binary Tree
3. Binary Search Tree
Check if a tree is binary search tree: Validate Binary Search Tree
Based on the property of Binary Search Tree, we can implement Binary Search to retrieve a value: Kth Smallest Element in a BST
4.Threaded Tree (Morris Tree)
Threaded Tree can guarantee O(n) time in traversal and O(1) space
(1) Preorder Traversal
(2) Inorder Traversal
(3) Postorder Traversal
5. Question Category
Preorder Traversal: Serialize and Deserialize Binary Tree,
Inorder Traversal: Recover Binary Search Tree,
Postorder Traversal: Binary Tree Postorder Traversal
Last updated
Was this helpful?