Problem List:
- 1. Maximum Depth of Binary Tree
- 2. Balanced Binary Tree
- 3. Path Sum
- 4. Flatten Binary Tree to Linked List
- 5. Validate Binary Search Tree (M)
- 6. Nearest Common Anscestor (M)
- 7. Binary Tree Longest Consecutive Sequence LintCode 595
- 8. Binary Tree Longest Consecutive Sequence II 好难
- 9. Binary Tree Paths
- 10. Minimum Subtree
- 11. Symmetric Binary Tree
- 12. Same Tree
- 13. Merge Two binary trees
- 14. Convert BST to Greater Tree
- 15. Convert Sorted Array to Binary Search Tree
104. Maximum Depth of Binary Tree
分治法:一分为二,左边一直往左边,右边一直往右边
class Solution {
public int maxDepth(TreeNode root) {
if (root==null){
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
}
打擂台递归:
private int depth;
public int maxDepth(TreeNode root) {
helper(root, 0);
return depth;
}
private void helper (TreeNode node, int curtDepth){
if(curtDepth > depth){
depth = curtDepth;
}
if(node == null){
return;
}
helper(node.left, curtDepth+1);
helper(node.right, curtDepth+1);
}
110. Balanced Binary Tree
感觉像上一题的follow up,完全可以在上一题分治法的基础上写出这个题。
class Solution {
public boolean isBalanced(TreeNode root) {
return helper(root) != -1;
}
private int helper(TreeNode root){
if(root == null){
return 0;
}
int left = helper(root.left);
int right = helper(root.right);
if (left == -1 || right == -1 || Math.abs(left - right) > 1){
return -1;
}
return Math.max(left, right) + 1;
}
}
112. Path Sum
找一条从头到尾的、和为target的路径,其实就是找一个leaf node such that 路径和为target。找一条路径可能比较模糊,但是找一个符合要求的leaf就会头脑清晰很多.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
return helper(root, 0, sum);
}
private boolean helper(TreeNode root, int sum, int target){
if (root == null){
return false;
}
if (root.val + sum == target && root.left == null && root.right == null){
return true;
}
return helper(root.left, sum + root.val, target) || helper(root.right, sum + root.val, target);
}
}
114. Flatten Binary Tree to Linked List
Traversal的解法太难了 不怎么会
private TreeNode last = null;
public void flatten(TreeNode root) {
if (root == null){
return;
}
if (last != null){
last.left = null;
last.right = root;
}
last = root;
TreeNode right = root.right;
flatten(root.left);
flatten(right);
}
以下解法是In place,因为我们没有new一个新的BT。那么这样就很简单,就是把左子树全部推到右边,利用stack,先push右边,再push左边。那么前几次pop的node就全是left child的node。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void flatten(TreeNode root) {
if (root == null){
return;
}
// Pushing all the left nodes to the right hand side
// Every node's left child has to be NULL
Stack <TreeNode> stack = new Stack <>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode current = stack.pop();
if (current.right != null){
stack.push(current.right);
}
if (current.left != null){
stack.push(current.left);
}
if (!stack.isEmpty()){
current.right = stack.peek();
}
current.left = null;
}
}
}
98. Validate Binary Search Tree
Long:防止overflow,简单递归,虽然我写不出来。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean helper(TreeNode root, long min, long max){
if(root == null){
return true;
}
if(root.val <= min || root.val >= max){
return false;
}
return helper(root.left, min, root.val) && helper(root.right, root.val, max);
}
}
236. Lowest Common Ancestor of a Binary Tree
分治法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null){
return root;
}
if(root == p || root == q){
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if(left != null && right != null){
return root;
}
if(left != null){
return left;
}
if(right != null){
return right;
}
return null;
}
}
Binary Tree Longest Consecutive Sequence
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: the root of binary tree
* @return: the length of the longest consecutive sequence path
*/
public int longestConsecutive(TreeNode root) {
// write your code here
return helper(root, null, 0);
}
private int helper (TreeNode root, TreeNode parent, int lengthWithoutRoot){
if (root == null){
return 0;
}
int currentLength = (parent != null && parent.val + 1 == root.val) ?
lengthWithoutRoot+1 : 1;
int left = helper(root.left, root, currentLength);
int right = helper(root.right, root, currentLength);
return Math.max(currentLength, Math.max(left, right));
}
}
Binary Tree Paths
遍历解法1:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if (root == null){
return res;
}
helper(res, root.val + "", root);
return res;
}
private void helper(List<String> res, String temp, TreeNode root){
// 递归终止条件
if(root == null){
return;
}
//遇到根结点 -> 加入答案
if (root.left == null && root.right == null){
res.add(temp);
return;
}
//要检查左子树是不是为空,不为空才能继续递归下去
if(root.left != null){
helper(res, temp + "->" + root.left.val + "", root.left);
}
// same as above
if(root.right != null){
helper(res, temp + "->" + root.right.val + "", root.right);
}
}
}
第二种解法:
分治法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList <>();
// 虽然走到了null,但是走过的路还是要记着
if (root == null){
return paths;
}
List<String> left = binaryTreePaths(root.left);
List<String> right = binaryTreePaths(root.right);
// 把左右两边到路径都接起来
for (String path : left){
paths.add(root.val + "->" + path);
}
for (String path : right){
paths.add(root.val + "->" + path);
}
// 当我们走到了叶节点,应该把叶子的值加进去,整个程序其实是倒序加入值的
if (paths.size() == 0){
paths.add(root.val + "");
}
return paths;
}
}
101. Symmetric Binary Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return isMirror(root, root);
}
private boolean isMirror(TreeNode r1, TreeNode r2){
//把二叉树想成一个个由不多于三个node的子树
//左右儿子都是空,这个小子树也是对称的
if(r1 == null && r2 == null){
return true;
}
//一个为空另一个不为空,这个小子树不是对称的
if(r1==null || r2==null){
return false;
}
//一棵树是对称的话,左右会对称,左儿子的右儿子会和右儿子的左儿子相等,左儿子的左儿子会和右儿子的右儿子相等。
return r1.val == r2.val && isMirror(r1.left, r2.right) && isMirror(r1.right, r2.left);
}
}
100. Same Tree
刚开始写的时候在递归函数里面多写了如果两个node的值相等就return true,然而这个是错误的。唯一预先判true的条件只能是两个node都为空(无法继续走,但是也不能给错),其他的都要在每个node相等的情况下才能继续true下去,最后一行就是这个重大意义。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
return isSame(p, q);
}
private boolean isSame (TreeNode r1, TreeNode r2){
if(r1 == null && r2 == null){
return true;
}
if(r1 == null || r2 == null){
return false;
}
if(r1.val != r2.val){
return false;
}
return isSame(r1.left, r2.left) && isSame(r1.right, r2.right);
}
}
617. Merge Two Binary Trees
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if(t1 == null){
return t2;
}
if(t2 == null){
return t1;
}
TreeNode t3 = new TreeNode(t1.val + t2.val);
t3.left = mergeTrees(t1.left, t2.left);
t3.right = mergeTrees(t1.right, t2.right);
return t3;
}
}
538. Convert BST to Greater Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
// Starting from the right-most node
// the right-most node won't change, but its parent will add the right-most
// then, the left child needs to add the parent
// Recursive
private int sum = 0;
public TreeNode convertBST(TreeNode root) {
helper(root);
return root;
}
private void helper(TreeNode root){
if(root == null){
return;
}
if (root.right != null){
helper(root.right);
}
sum += root.val;
root.val = sum;
if(root.left != null){
helper(root.left);
}
}
}
108. Convert Sorted Array to Binary Search Tree
Intuition: binary search,always take the middle pt
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return helper(nums, 0, nums.length - 1);
}
private TreeNode helper(int[] nums, int start, int end){
if(start > end){
return null;
}
int mid = (start + end)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = helper(nums, start, mid - 1);
root.right = helper(nums, mid + 1, end);
return root;
}
}