[US Giants] 七. Binary Tree

Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example

Given binary tree A = {3,9,20,#,#,15,7}, B = {3,#,20,15,7}

A)  3            B)    3 
   / \                  \
  9  20                 20
    /  \                / \
   15   7              15  7

The binary tree A is a height-balanced binary tree, but B is not.

思路:如果左右subtree有一个不平衡,就不符合要求

         如果左右subtree都是平衡的,但是要符合两边高度差不能大于1

/**
 * 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: True if this Binary tree is Balanced, or false.
     */
    
    public boolean isBalanced(TreeNode root) {
        return helper(root)!=-1;
    }
    
    private int helper(TreeNode root){
        if(root==null){
            return 0;
        }
     
        int leftDepth=helper(root.left);
        int rightDepth=helper(root.right);
        if(leftDepth==-1 || rightDepth==-1 || Math.abs(leftDepth-rightDepth)>1){
            return -1;
        }
        return Math.max(leftDepth,rightDepth)+1;
    }
}
Insert Node in a Binary Search Tree

Given a binary search tree and a new tree node, insert the node into the tree. You should keep the tree still be a valid binary search tree.

You can assume there is no duplicate values in this tree + node.

Example

Given binary search tree as follow, after Insert node 6, the tree should be:

  2             2
 / \           / \
1   4   -->   1   4
   /             / \ 
  3             3   6
Challenge Can you do it without recursion?
思路:由于是BST,而且题目给出条件tree+node里没有重复值,因此node的去向就是两种,要么root左边,要么root右边

         如果node的值比当前root值小,去向就是左边,继续找,如果左边值不为null,继续判断,如果为null,就直接赋值node为这个位置

         如果node的值比当前root值大,去向就是右边,继续找,如果右边值不为null,继续判断,如果为null,就直接赋值node为这个位置       

/**
 * 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 {                                         //non-recursion
    /**
     * @param root: The root of the binary search tree.
     * @param node: insert this node into the binary search tree
     * @return: The root of the new binary search tree.
     */
    public TreeNode insertNode(TreeNode root, TreeNode node) {
        if(root==null){
            return node;
        }
        
        TreeNode cur=root;
        while(true){                                           //因为while(true)是一个无限循环,表达式一直为真
            if(node.val<cur.val){                              //需要break跳出循环
                if(cur.left!=null){
                   cur=cur.left; 
                }else{
                   cur.left=node;
                   break;
                }
            }else if(node.val>cur.val){
                if(cur.right!=null){
                   cur=cur.right; 
                }else{
                   cur.right=node;
                   break;
                }
            }
        }
        return root;
    }
}

/**
 * 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 {                                         //recursion
    /**
     * @param root: The root of the binary search tree.
     * @param node: insert this node into the binary search tree
     * @return: The root of the new binary search tree.
     */
    public TreeNode insertNode(TreeNode root, TreeNode node) {
        if(root==null){
            return node;                                        //这里写成root=node是一样的
        }
        if(node.val<root.val){
            root.left=insertNode(root.left, node);
        }else{                                                  //因为题目指出没有duplicates,因此else的情况就是
            root.right=insertNode(root.right, node);            //node.val>root.val
        }
        return root;
    }
}
Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

You may assume that duplicates do not exist in the tree.

Example

Given in-order [1,2,3] and pre-order [2,1,3], return a tree:

  2
 / \
1   3
思路:preorder的第一个元素就是要建立的二叉树的root,在inorder数组里找到root的位置,也就是值等于prorder[pstart]的位置,记为pos

         pos的前面的就是左子树,pos的后面的就是右子树

注意:左右子树递归的时候,找preorder开始和结束位置的边界的时候,长度可以由inorder的长度来计算

         例如root.left=build(inoder,istart,pos-1,preorder,pstart+1,end);

         end值的计算:根据inorder部分计算左子树占据的数组长度,pos-1-istart+1=pos-istart

         因此preorder这部分的长度也是pos-istart,又因为preorder从pstart开始,所以最后知end为pstart+pos-istart

/**
 * 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 preorder : A list of integers that preorder traversal of a tree
     *@param inorder : A list of integers that inorder traversal of a tree
     *@return : Root of a tree
     */
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder==null || inorder==null){
            return null;
        }
        if(preorder.length!=inorder.length){
            return null;
        }
        return build(inorder,0,inorder.length-1,preorder,0,preorder.length-1);      
    }
    
    private TreeNode build(int[] inorder,int istart,int iend,int[] preorder,int pstart,int pend){
        if(istart>iend){                                                         //这边写成pstart<pend也是一样的
            return null;
        }
        int pos=findPosition(inorder,istart,iend,preorder[pstart]);
        TreeNode root=new TreeNode(preorder[pstart]);
        root.left=build(inorder,istart,pos-1,preorder,pstart+1,pstart+pos-istart); 
        root.right=build(inorder,pos+1,iend,preorder,pstart+pos-istart+1,pend);  //preorder的右边开始位置是
        return root;                                                             //preorder左边结束位置+1
    } 
     
    private int findPosition(int[] arr,int start,int end,int pos){
        for(int i=start;i<=end;i++){
            if(arr[i]==pos){
                return i;
            }
        }
        return -1;
    }
}
Construct  Binary Tree from inorder and postorder traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

You may assume that duplicates do not exist in the tree.

Example

Given inorder [1,2,3] and postorder [1,3,2], return a tree:

  2
 / \
1   3

思路:和inorder,preorder建树的思路一样

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder.length!=postorder.length){
            return null;
        }
        return build(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
    }
    
    public TreeNode build(int[] inorder,int istart,int iend, int[] postorder,int pstart,int pend) {
        if(istart>iend){
            return null;
        }
        TreeNode root=new TreeNode(postorder[pend]);
        int pos=finPos(inorder,istart,iend,postorder[pend]);
        root.left=build(inorder,istart,pos-1,postorder,pstart,pstart+pos-istart-1);
        root.right=build(inorder,pos+1,iend,postorder,pstart+pos-istart,pend-1);
        return root;
    }
    
    private int finPos(int[] arr,int start,int end,int pos){
        for(int i=start;i<=end;i++){
            if(arr[i]==pos){
                return i;
            }
        }
        return -1;
    }
}
Remove Node in Binary Search Tree

Given a root of Binary Search Tree with unique value for each node. Remove the node with given value. If there is no such a node with given value in the binary search tree, do nothing. You should keep the tree still a binary search tree after removal.

Example

Given binary search tree:

    5
   / \
  3   6
 / \
2   4            当前root下有两个结点,找右面最小值,此时为4,把4赋值到当前root,再对4进行递归,此时value=4,下面没有结点,返回null

Remove 3, you can either return:

    5
   / \
  2   6
   \
    4

or

    5
   / \
  4   6
 /
2                本题解法就是最后建立这样一颗树
思路:考虑到三种情况:

         要删除的node下面没有结点,直接把此结点设为null

         要删除的node下面只有一个或左或右的结点,或者是说只有左子树或者只有右子树,直接返回这颗树

         要删除的node下面有两个结点,找到右子树的最小值结点,根据BST知,最小值结点一定在左面,或者就是它自己,

         把找到的最小值赋值到当前node的值,

         对于当前node的右子树再进行同样的递归,此时要递归删除的value就是刚才找到的右子树的最小值点

/**
 * 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 the binary search tree.
     * @param value: Remove the node with given value.
     * @return: The root of the binary search tree after removal.
     */
    public TreeNode removeNode(TreeNode root, int value) {
        if(root==null){
            return null;
        }
        
        if(value>root.val){
            root.right=removeNode(root.right, value);
        }else if(value<root.val){
            root.left=removeNode(root.left, value);
        }else{
            if(root.left==null && root.right==null){
                return null;
            }
            if(root.left==null){
                return root.right;
            }
            if(root.right==null){
                return root.left;
            }
            TreeNode minRight=findNode(root.right);
            root.val=minRight.val;
            root.right=removeNode(root.right,minRight.val);       //此时要递归的value就是刚才找到的右子树最小值
        }
        return root;
    }
    
    private TreeNode findNode(TreeNode cur){
        while(cur.left!=null){
            cur=cur.left;
        }
        return cur;
    }
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值