Each node of the tree has at most two children - a left and a right child.
Complete Binary Tree
All the levels of the tree are filled completely except the lowest level nodes which are filled from as left as possible.
Perfect Binary Tree
A binary tree of height h having the maximum number of nodes is a perfect binary tree.
Full Binary Tree
A full Binary tree is a special type of binary tree in which every parent node/internal node has either two or no children. It is also known as a proper binary tree.
Tree Traversal
Iterative Preorder Traversal
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicstatic List<Integer> preorderTraversal(TreeNode root) { List<Integer> results = newArrayList<>(); if(root==null) return results; Stack<TreeNode> stack = newStack<>(); stack.push(root); //when it comes to the last node, stack will be empty while(!stack.empty()){ TreeNodecur= stack.pop(); results.add(cur.val); if(cur.right!=null) stack.push(cur.right); if(cur.left!=null) stack.push(cur.left); }
return results; }
Iterative Inorder Traversal
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicstatic List<Integer> inorderTraversal(TreeNode root) { List<Integer> res = newArrayList<>(); TreeNodecur= root; Stack<TreeNode> stack = newStack<>(); while(cur!=null || !stack.empty()){ //left while(cur!=null){ stack.push(cur); cur = cur.left; } //root and right if(!stack.empty()){ cur = stack.pop(); res.add(cur.val); cur = cur.right; } } return res; }