二叉搜索树的判断 leetcode原题

来源:互联网 发布:华为软件培训 编辑:程序博客网 时间:2024/06/08 16:45

二叉查找树(Binary Search Tree)

(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树(这也是判断二叉搜索树的标准,即条件)

(1) 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 

(2)若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;

(3)它的左、右子树也分别为二叉排序树

leetcode题目:

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

以下程序是判断一棵树

判断过程:

(1)从根节点开始判断:左右两个节点的大小是否符合:左节点值<根节点值<右节点值,并依次遍历判断整棵树左子树所有节点和右子树所有节点是否满足二叉搜索树性质(1)和(2);

(2)根节点检测完成后,开始左右子树的遍历,判断它们是不是二叉搜索树

class TreeNode {
     int val;
     TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
  }
publicclass Solution {
    publicstatic boolean IsSubtreeLessThan(TreeNode t, intval) {
        if(t == null)
            returntrue;
        return(t.val < val && IsSubtreeLessThan(t.left, val) && IsSubtreeLessThan(t.right, val));
    }
    publicstatic boolean IsSubtreeMoreThan(TreeNode t, intval) {
        if(t==null)
            returntrue;
        return(t.val>val && IsSubtreeMoreThan(t.left, val) && IsSubtreeMoreThan(t.right, val));
    }
 
    publicboolean isValidBST(TreeNode root) {
        if(root == null)
            returntrue;
        return(IsSubtreeLessThan(root.left, root.val) && IsSubtreeMoreThan(root.right, root.val)
        && isValidBST(root.left) && isValidBST(root.right));//对应上述“”判断过程“”
    }
}
    添加笔记


阅读全文
0 0