第54题 Validate Binary Search Tree

来源:互联网 发布:豪门体验知乎 编辑:程序博客网 时间:2024/06/06 10:43

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.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1  / \ 2   3    /   4    \     5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
Hide Tags
 Tree Depth-first Search
Solution in Java:
/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean isValidBST(TreeNode root) {                 return valid(root, Integer.MIN_VALUE, Integer.MAX_VALUE);        }    public boolean valid(TreeNode node, int leftMargin, int rightMargin){       if(node==null) return true;       if(node.val==Integer.MIN_VALUE&&node.left!=null   || node.val==Integer.MAX_VALUE&&node.right!=null) //判断边界条件!!            return false;       else return node.val<=rightMargin&&node.val>=leftMargin && valid(node.left, leftMargin, node.val-1) && valid(node.right,node.val+1, rightMargin);    }}

Note: 规定边界值,查看是否在合法范围内。
注意如果该结点值为Integer.MIN_VALUE,则表示已为最小值,则它不能有左子树。
如果该结点值为Integer.MAX_VALUE,则表示已为最大值,则它不能有右子树。
判定时如果要递归左子树,则右边界为node.val-1;如果要递归右子树,则左边界为node.val+1。
Solution in Java 2:
<span style="font-size:18px;">public class Solution {    List<Integer> list = new ArrayList<Integer>();            public boolean isValidBST(TreeNode root) {          if (root == null) return true;          if (root.left == null && root.right == null) return true;          inOrderTraversal(root);          for (int i = 1; i < list.size(); i++) {             if (list.get(i-1)>=list.get(i)) return false;           }          return true;       }            public void inOrderTraversal(TreeNode root) {          if (root == null) return;          inOrderTraversal(root.left);          list.add(root.val);          inOrderTraversal(root.right);      }  }</span>

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


















0 0
原创粉丝点击