Tree总结
树结构问题因为容易写出解法,因此经常出现在面试题中
1. 树的种类
1) Tree
2) Binary Trees
3) Binary Search Trees(BST) : used to sorted or ordered data. //解决方案:recursion
查找操作(fast and simple):O(logn)
插入和删除:O(logn)
打印:O(n)
4) Heap: find the maximum value / minimum value(min-heap) in constant time.
插入和删除:O(logn)
查找:O(n) ,因为除了顶点,左右子书是无序的
2. 通常的查询方法
注意:如果查找的树结构是无序的,时间复杂度是O(n),所以复杂的树要避免使用普通的树结构
1)BFS :空间开销大
2) DFS
3. Traversals
当需要遍历树中的每个点时使用的方法,遍历方法有很多。 // recursive
最寻常的Depth-first-traversals for binary tree的种类
1) Pre-order : a node is always visited before any its children, then left first
2) In-order : The left subtree is visited first, then the node itself, and then the nodes's right subtree.
3) Post-order: left, right, node. A node is always visited after all its children.
树类型的经典问题:
1. 求树高
思路:在遇到树问题时,先考虑是否能使用recursive的方法解决。本题中,我们可以看出,任意子节点的树高是它两个子节点树高的最大值+1
public static int treeHeight( Node n){ if(n == null) return 0; return 1 + Math.max( treeHeight(n.left), treeHeight(n.right) ); }
2. Pre-order traversal
思路 1 :pre-order traversal 要求先打印root node,然后是左子树,再右子树。注意:左子树是直接遍历到底的。从recursive的观点来看,这个问题可以分成三个部分
1) 打印root node
2) 左子树
3) 右子树
public static void preOrderT(Node n) { if(n == null) return; System.out.println(n.value); //意思意思 preOrderT(n.left); preOrderT(n.right); }
inorder和postorder同理
思路 2 (非 recursion):recursive的方法在原理上与栈类似,因此本能应选择栈作为替代的数据结构
public static void preOrderTStack(Node n) { Stack<Node> stack = new Stack<>(); stack.push(n); while(!stack.isEmpty()) { Node curr = stack.pop(); System.out.println(curr.value); //调用都是意思意思 if(curr.right != null) stack.push(curr.right); if(curr.left != null) stack.push(curr.left); } }
3. Lowest Common Ancestor
二叉树,给两个子节点,求他们的共同的,最小的,父节点
思路:因为是二叉树,只要找到一个点,数值在两个数之间久行。注意:这里虽然可以用recursion,但是因为recursion更适合在不同的branch内查询,或者查询node的规律,因此用iteration就可以遍历
public static Node minimumHeightA(Node n, Node v1, Node v2) {
int min = Math.min(v1.value, v2.value);
int max = Math.max(v1.value, v2.value);
while(n!= null) {
if(n.value > max) {
n = n.left;
}else if(n.value < min) {
n = n.right;
} else {
return n;
}
}
return null;
}
4. Binary Tree to Heap