The Tree ||

Binary Tree Right Side View :*** This one is a little tricky, how to ensure there is only the most right node in the res list for each lvl. 学习中间变量的使用,找到正确的中间变量能简化问题,解决问题。Further understand the way recursion works.
public class Solution {
    public List
   
   
    
     rightSideView(TreeNode root) {
        List
    
    
     
      res = new ArrayList
     
     
      
      ();
        if(root == null){
            return res;
        }
        helper(res,root,0);
        return res;
    }
    public void helper(List
      
      
       
        res, TreeNode node, int lvlNo){
        if(res.size() <= lvlNo){
            res.add(node.val);
        }
        
        if(node.right != null)
            helper(res,node.right,lvlNo+1);
        if(node.left != null)
            helper(res,node.left,lvlNo+1);
    }
}
      
      
     
     
    
    
   
   

Construct Binary Tree from Inorder and Postorder Traversal :**** This question is very inspiring. Notice the return condition of returning null. The overall logic is tricky but clear, find root through postorder(always at very end), then decide left and right through inorder(nodes are not duplicate!). 
public class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder == null || postorder == null || inorder.length == 0|| postorder.length == 0){
            return null;
        }
        return helper(inorder,postorder,0,inorder.length-1,0,postorder.length-1);
        
    }
    public TreeNode helper(int[] inorder, int[] postorder, int s1, int e1, int s2, int e2){
        if(s2 > e2 || s1 > e1){
            return null;
        }
        TreeNode root = new TreeNode(postorder[e2]);
        int root_index = -1;
        for(int i=s1; i<=e1;i++){
            if(inorder[i] == root.val){
                root_index = i;
                break;
            }
        }
        if(root_index == -1)
            return null;
        int left_size = root_index - s1;
        int right_size = e1 - root_index;
        root.left = helper(inorder,postorder,s1,root_index-1,s2,s2+left_size-1);
        root.right = helper(inorder,postorder,root_index+1,e1,e2-right_size,e2-1);
        return root;
    }
}

Lowest Common Ancestor of a Binary Tree :**** This one is tricky. Nothing much to say, remember it. 
if(root == null){
            return null;
        }
        
        if(root == p || root == q){
            return root;
        }
        
        TreeNode l = lowestCommonAncestor(root.left,p,q);
        TreeNode r = lowestCommonAncestor(root.right,p,q);
        
        if(l != null && r != null){
            return root;
        }
        
        return l != null ? l:r;

Recover Binary Search Tree : **** This one is tricky. (study this one with Flatten Binary Tree to Linked List  , see how this keep track of pre-node). Remember this one. See analysis here  Code_Ganker
public class Solution {
    public void recoverTree(TreeNode root) {
        TreeNode[] pre = new TreeNode[1];
        pre[0] = null;
        List
    
    
     
      res = new ArrayList
     
     
      
      ();
        helper(root,pre,res);
        if(res.size() > 0){
            int  temp = res.get(0).val;
            res.get(0).val = res.get(1).val;
            res.get(1).val = temp;
        }
        return;
    }
    
    public void helper(TreeNode node, TreeNode[] pre, List
      
      
       
        res){
        if(node == null)
            return;
        helper(node.left,pre,res);
        if(pre[0] != null && pre[0].val > node.val){
            if(res.isEmpty()){
                res.add(pre[0]);
                res.add(node);
            }else{
                res.set(1,node);
            }
        }
        pre[0] = node;
        helper(node.right,pre,res);
    }
}
      
      
     
     
    
    

Binary Tree Maximum Path Sum: *** Tricky one. The variable to main and the variable to return is different. Notice that making sure L and R always larger than 0 will simplify the process of maintaining max_value a lot.
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxPathSum(TreeNode root) {
        int[] res = new int[1];
        res[0] = Integer.MIN_VALUE;
        helper(res,root);
        return res[0];
    }
    
    public int helper(int[] res, TreeNode node){
        if (node == null)
            return 0;
        int L = helper(res,node.left);
        int R = helper(res,node.right);
        L = Math.max(L,0);
        R = Math.max(R,0);
        res[0] = Math.max(res[0], R + L + node.val);
        return Math.max(L,R) + node.val;
    }
}

Count Complete Tree Nodes : *** Brute force will take O(n) and ETL. Remember this one, which uses properties of complete Binary tree, which is there must be one child subtree could be calculated by  (1<<h) - 1 ! So we can skip scanning this subtree.
public class Solution {
    public int countNodes(TreeNode root) {
        if(root == null){
            return 0;
        }
        int l = leftDFS(root);
        int r = rightDFS(root);
        if(l==r){
            return (1<
    
    

Validate Binary Search Tree : *** Tricky one. Very similar to  Recover Binary Search Tree . This could be done exactly follow the same way as recover BST though, but not necessary. Since we only need to discover any mis-order instance instead of fixing them, we only need to return true or false then. Remember this. Especially when to update the pre variable.
public class Solution {
    public boolean isValidBST(TreeNode root) {
        TreeNode[] pre = {null};
        return helper(root,pre);
    }
    
    public boolean helper(TreeNode node, TreeNode[] pre){
        if(node == null)
            return true;
        if( ! helper(node.left,pre) )
            return false;
        if(pre[0] != null && pre[0].val >= node.val)
            return false;
        pre[0] = node;
        if( !helper(node.right,pre) )
            return false;
        return true;
    }
}

subtree : ***
//You have two every large binary trees: T1, with millions of nodes, and T2, 
//with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1.
public class Solution {
    /**
     * @param T1, T2: The roots of binary tree.
     * @return: True if T2 is a subtree of T1, or false.
     */
    public boolean isSubtree(TreeNode T1, TreeNode T2) {
        // write your code here
        if(T2 == null)
            return true;
        return helper(T1,T2);
    }
    public boolean helper(TreeNode T1, TreeNode T2){
        if(T1 == null && T2 == null)
            return true;
        if(T1 == null || T2 == null)
            return false;
        
        if(T1.val == T2.val){
            boolean right = helper(T1.right, T2.right);
            boolean left = false;
            if(right)
                 left = helper(T1.left, T2.left);
            if(left)
                return true;
        }
        //This is easy to make mistake. We should start over if cur node is not
        //a possible subtree root.Thus here is not a if...else structure
        boolean right = helper(T1.right, T2);
        boolean left = false;
        if(!right)
            left = helper(T1.left, T2);
        return right || left;
        
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值