Binary Tree
Definition: at most two children node.
Binary Tree Example:
10 ==root
/ \
13 15 cur
/ \ / \
21 72 12 2
/ \
null null
class TreeNode{
int value;
TreeNode * left;
TreeNode * right;
TreeNode * parent //point to this node's parent node.
}
面試常見題型:
基本知識點1: tree traverse
1. pre-order.
2.in-order.
3.post-order.
關鍵點:base case通常就是葉子節點下面的空節點。
Balanced binary tree:
對於樹的任意一個節點,左子樹和右子樹的高度差不超過1。
Complete binary tree(完全二叉樹)
底層是一個數組,數組內部的數字必須是連續的,不能有空余的內存空間。
Binary Search Tree(二叉查找樹)
10
/ \
5 15
/ \ / \
2 7 12 20
注意:對於根節點10,必須整個左子樹(左子樹上的所有節點)都必須比10小,整個右子樹(右子樹上的所有節點)必須比10大。
同時binary search tree不允許有重復的node;
Binary tree 往往是最常見的和recursion結合最緊密的面試題目類型。
理由:
1.每層的node所具備的性質,傳遞的值和下一層的性質往往一致,比較容易定義recursive rule。
2.base case: null pointer under the leaf node.
3.Example1:int getHeight(Node root)
4.Example2:統計tree里面有多少個node。
常見面試題型:
How to get integer value(height) for a problem with size = n? But how?
GetHeight of a binary tree?
public int getHeight(TreeNode root){
if(root == null){
return 0;
}
int left = getHeight(root.left);
int right = getHeight(root.right);
return 1 + Math.max(left,right);
}
Time = O(n);
space = O(n) == O(height);
---------------------------------------------------------------------------------------------------------------------------
Q3:How to determine whether a binary tree is a balanced binary tree?
public boolean isBalanced(TreeNode tree){
if(root == null){
return true;
}
int left = getHeight(root.left);
int right = getHeight(root.right);
if(Math.abs(left - right) > 1){
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
}
時間復雜度分析:
isBalanced(n/2 + n/2)
/ \
getHeight getHeight
(n/4 + n/4) (n/4 + n/4)
因為是一個平衡二叉樹所以:層數logn So: Time : O(nlogn)
---------------------------------------------------------------------------------------------------------------------------
Q4:怎么判斷一顆二叉樹左右兩邊是不是對稱的?
10
5a | 5b
1a 3a | 3b 1b
2a4a 6a8a | 8b6b 4b2b
public boolean isSymmetric(TreeNode noe,TreeNode two){
if(one == null && two == null){
return true;
}
if(one ==null || two == null){
return false;
}
if(one.value == two.value){
return false;
}
return isSymmetric(one.left,two.right) && isSymmetric(one.right,one.left);
}
Time = O(n);
space = O(n) -> O(height) if the tree is balaced -> O(logn)
---------------------------------------------------------------------------------------------------------------------------
Q5: