[leetcode]二叉搜索树&平衡二叉树

1.二叉搜索树 BST
概念:
①所有非叶子节点至多拥有两个儿子
②所有节点存储一个关键字
非叶子节点的左指针指向小于其关键字的子树,右指针指向大于其关键字的子树
④二叉搜索树的中序遍历是不递减的

题目描述:
Given a binary tree, determine if it is a valid binary search tree (BST).

思路:
根据④可得,可中序遍历该树,看是否不递减的,若不满足,则不是二叉搜索树

代码:

public class Solution {
    TreeNode pre=null;
    public boolean isValidBST(TreeNode root) {
        if(root!=null){
            if(!isValidBST(root.left)){
                return false;
            }
            if(pre!=null&&root.val<=pre.val){
                return false;
            }
            pre=root;
            return isValidBST(root.right);
        }
        return true;
    }
}

2.平衡二叉搜索树
概念:平衡二叉搜索树,其是一棵空树或其左右子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

题目描述:
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.

思路:
遍历到一个节点时,检查其左子树和右子树的高度差是否满足平衡二叉搜索树的性质,若满足再去递归检查其左子树和右子树是否满足。

代码:

public class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root==null){
            return true;
        }
        int height1=getHeight(root.left);
        int height2=getHeight(root.right);
        if((height1-height2)>=-1&&(height1-height2)<=1){
            return true&&isBalanced(root.left)&&isBalanced(root.right);
        }
        else{
            return false;
        }
    }
    
    public int getHeight(TreeNode root){
        if(root==null){
            return 0;
        }
        if(root.left==null&&root.right==null){
            return 1;
        }
        else{
            int height=1+Math.max(getHeight(root.left),getHeight(root.right));
            return height;
        }
    }
     
}

猜你喜欢

转载自blog.csdn.net/qq_41618373/article/details/83748247