二叉查找树

1 11 搜索区间

    public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) {
        // write your code here
        ArrayList<Integer> res = new ArrayList<>();
        help(root, k1, k2, res);
        return res;
    }
    public void help(TreeNode root, int k1, int k2, ArrayList<Integer> res){
        if (root == null) return;
        if (k1 < root.val){
            help(root.left, k1, k2, res);
        }
        if (k1 <= root.val && root.val <= k2){
            res.add(root.val);
        }
        if (root.val < k2){
            help(root.right, k1, k2, res);
        }
    }
View Code

2 85 插入节点

    public TreeNode insertNode(TreeNode root, TreeNode node) {
        if (root == null){
            return node;
        }
        if (root.val > node.val) {
            root.left = insertNode(root.left, node);
        } else {
            root.right = insertNode(root.right, node);
        }
        return root;
    }
View Code

3 661 Conver BST to Greater Tree

public class Solution {
    /**
     * @param root the root of binary tree
     * @return the new root
     */
     int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        // Write your code here
        help(root);
        return root;
    }
    public TreeNode help(TreeNode root){
        if (root == 0) return;
        if (root.right != null){
            help(root.right);
        }
        sum += root.val;
        root.val = sum;
        if (root.left != null){
            help(root.left);
        }
    }
}
View Code

4 95 验证二叉查找树

    public boolean isValidBST(TreeNode root) 
    {
        return help(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    public boolean help(TreeNode root, long min, long max);
    {
        if (root == null) return true;
        if (root.val <= min || root.val >= max) return false;
        return help(root.left, min, Math.min(root.val, max)) &&
               help(root.right, Math.max(root.val, min));
    }
View Code

 

posted on 2017-06-15 14:08  wheleetcode  阅读(79)  评论(0编辑  收藏  举报