【LeetCode】Validate Binary Search Tree ——合法二叉树

【题目】

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) 左子树的值都比根节点小;2) 右子树的值都比根节点大;3) 左右子树也必须满足上面两个条件。

需要注意的是,左子树的所有节点都要比根节点小,而非只是其左孩子比其小,右子树同样。这是很容易出错的一点是,很多人往往只考虑了每个根节点比其左孩子大比其右孩子小。如下面非二分查找树,如果只比较节点和其左右孩子的关系大小,它是满足的。

     5
  /    
4      10
      /      
    3        11

【错误代码示范】【NA】

 1 /** 
 2  * Definition for binary tree 
 3  * public class TreeNode { 
 4  *     int val; 
 5  *     TreeNode left; 
 6  *     TreeNode right; 
 7  *     TreeNode(int x) { val = x; } 
 8  * } 
 9  */  
10 public class Solution {  
11     public boolean isValidBST(TreeNode root) {  
12         if (root == null) return true;  
13         if (root.left != null && root.val <= root.left.val) return false;  
14         if (root.right != null && root.val >= root.right.val) return false;  
15         return isValidBST(root.left) && isValidBST(root.right);  
16     }  
17 }  

正确解法:中序遍历

二分查找树的中序遍历结果是一个递增序列。

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool isValidBST(TreeNode *root) {
13         if(root==NULL) return true;
14         bool res = true;
15         res&=isValidBST(root->left);
16         if(pre!=NULL&&pre->val>=root->val) res=false;
17         pre=root;
18         res&=isValidBST(root->right);
19         return res;
20     }
21     TreeNode *pre=NULL;
22 };
原文地址:https://www.cnblogs.com/zl1991/p/7055488.html