LintCode - Ladder3 Binary Tree & Divide Conquer
Oct 14th
Tree 结构是否会比其它结构更难建立? no!! 创建的时间都是一样的,每个元素都添加一遍 一定是O(n) 的时间复杂度
Before the Start
Basic Knowledge:
mycodeschool video
Height of the tree: no of edges in longest -> height of an empty tree = -1, height of tree with 1 node = 0
Binary Tree
one node only have two child node, one node can have no more than two child node
Strict binary tree 2 or 0
Complete Binary Tree -> all levels except possibly the last are completely filled
Perfect Binary Tree -> Complete binary tree in which all levels are full.
Balanced/ Unbalanced Tree -> difference between height of left and right subtree for every node is not more than 1
Binary Search Tree: binary tree + left <= root <= right
Implement of binary tree using:
a. dynamically created nodes
b. arrays (most for complete binary tree and heap)
Divide and Conquer
参考 Merge sort中的分治法思想
1.Binary Tree Preorder Traversal --AC
Des: implement the preorder traversal
Think:
- Preorder: ROOT -> LEFT -> RIGHT result.add(root.val), traverse(root.left), traverse(root.right)
- No recursion -> use stack, according to the preorder, push + pop the key point is understanding the whole process of preorder traversal
错误总结:
- 在一个function 内 定义两个function -> 注意花括号的位置
- return in a '''void''' function -> It just exits the method at that point. Once return is executed, the rest of the code won't be executed.
知识点:
定义一个新的数组,定义一个新的栈,定义一个新的function
'''java
List
Stack
void traverse(List
if (root == null) { //递归的出口 -> leaf node
return; //just exit the method here
}
'''
2.Subtree with Maximum Average -Give up Skip
Des: Binary tree, the subtree
Think: Find all the subtree, calculate the average, find the max
3.Binary Tree Paths - JiuZhang example
Des: Given a binary tree, return all root-to-leaf paths.
Format:
知识点:
1.for each loop in java
'''
for (String path : leftPaths) {
paths.add(root.val + "->" + path);
}
2.注意变量中的单复数的命名 -> 体现编程功底的细节
3.二叉树问题中 divide conquer 基本可以无脑考虑left subtree + right subtree
Oct 17th
1.Binary Tree Paths
Des: Given a binary tree, return all root-to-leaf paths.
Think: Recursion solution
如何定义递归,root 节点, 保留root
整个function的定义能够直接反应从原问题到子问题的分解
错误总结:
- 定义新变量需要声明类型
- return语句 与add语句要分开
2. Minimum Subtree --NO CLUE
Des: Given a binary tree, find the subtree with minimum sum
Think:
D & C
sum: 从根节点开始加起,
最后的比较筛选过程如何实现??-> 所有的sum都需要筛选一遍
Solution: 定义一个新的helper() function 去完成两件事情
- 求出以root为根节点的subtree 的sum值 sum = helper(root.left) + helper(root.right+) + root.val;
- 将所有的sum值依次进行比较找出最小值