LeetCode: Validate Binary Search Tree 解题报告

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.
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

SOLUTION 1:

使用Iterator 中序遍历的方法,判断整个数列是否保持增序即可。

算法思想:

http://www.cnblogs.com/shuaiwhu/archive/2011/04/20/2065055.html

1.采用栈的话,先寻找最左边的节点,把经过的节点都存入栈中,第一个被弹出来的为最左节点,那么访问其右子树,对右子树也像前面一样遍历,整个流程跟递归一样。

 1 public boolean isValidBST1(TreeNode root) {
 2         // Just use the inOrder traversal to solve the problem.
 3         if (root == null) {
 4             return true;
 5         }
 6
 7         Stack<TreeNode> s = new Stack<TreeNode>();
 8         TreeNode cur = root;
 9
10         TreeNode pre = null;
11
12         while(true) {
13             // Push all the left node into the stack.
14             while (cur != null) {
15                 s.push(cur);
16                 cur = cur.left;
17             }
18
19             if (s.isEmpty()) {
20                 break;
21             }
22
23             // No left node, just deal with the current node.
24             cur = s.pop();
25
26             if (pre != null && pre.val >= cur.val) {
27                 return false;
28             }
29
30             pre = cur;
31
32             // Go to the right node.
33             cur = cur.right;
34         }
35
36         return true;
37     }

SOLUTION 2:

引自大神的思想:http://blog.csdn.net/fightforyourdream/article/details/14444883

我们可以设置上下bound,递归左右子树时,为它们设置最大值,最小值,并且不可以超过。

注意:下一层递归时,需要把本层的up 或是down继续传递下去。相当巧妙的算法。

 1 /*
 2         SOLUTION 2: Use the recursive version.
 3         REF: http://blog.csdn.net/fightforyourdream/article/details/14444883
 4     */
 5     public boolean isValidBST2(TreeNode root) {
 6         // Just use the inOrder traversal to solve the problem.
 7         if (root == null) {
 8             return true;
 9         }
10
11         return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE);
12     }
13
14     public boolean dfs(TreeNode root, long low, long up) {
15         if (root == null) {
16             return true;
17         }
18
19         if (root.val >= up || root.val <= low) {
20             return false;
21         }
22
23         return dfs(root.left, low, root.val)
24            && dfs(root.right, root.val, up);
25     }

SOLUTION 3:

同样是递归,但是把左右子树的min, max值返回,与当前的root值相比较。比较直观。

 1 /*
 2         SOLUTION 3: Use the recursive version2.
 3     */
 4     public boolean isValidBST3(TreeNode root) {
 5         // Just use the inOrder traversal to solve the problem.
 6         if (root == null) {
 7             return true;
 8         }
 9
10         return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE);
11     }
12
13     public class ReturnType {
14         int min;
15         int max;
16         boolean isBST;
17         public ReturnType (int min, int max, boolean isBST) {
18             this.min = min;
19             this.max = max;
20             this.isBST = isBST;
21         }
22     }
23
24     // BST:
25     // 1. Left tree is BST;
26     // 2. Right tree is BST;
27     // 3. root value is bigger than the max value of left tree and
28     // smaller than the min value of the right tree.
29     public ReturnType dfs(TreeNode root) {
30         ReturnType ret = new ReturnType(Integer.MAX_VALUE, Integer.MIN_VALUE, true);
31         if (root == null) {
32             return ret;
33         }
34
35         ReturnType left = dfs(root.left);
36         ReturnType right = dfs(root.right);
37
38         // determine the left tree and the right tree;
39         if (!left.isBST || !right.isBST) {
40             ret.isBST = false;
41             return ret;
42         }
43
44         // 判断Root.left != null是有必要的,如果root.val是MAX 或是MIN value,判断会失误
45         if (root.left != null && root.val <= left.max) {
46             ret.isBST = false;
47             return ret;
48         }
49
50         if (root.right != null && root.val >= right.min) {
51             ret.isBST = false;
52             return ret;
53         }
54
55         return new ReturnType(Math.min(root.val, left.min), Math.max(root.val, right.max), true);
56     }

SOLUTION 4:

使用一个全局变量,用递归的中序遍历来做,也很简单(但全局变量主页君不推荐!)

 1 /*
 2         SOLUTION 4: Use the recursive version3.
 3     */
 4     TreeNode pre = null;
 5
 6     public boolean isValidBST(TreeNode root) {
 7         // Just use the inOrder traversal to solve the problem.
 8         return dfs4(root);
 9     }
10
11     public boolean dfs4(TreeNode root) {
12         if (root == null) {
13             return true;
14         }
15
16         // Judge the left tree.
17         if (!dfs4(root.left)) {
18             return false;
19         }
20
21         // judge the sequence.
22         if (pre != null && root.val <= pre.val) {
23             return false;
24         }
25         pre = root;
26
27         // Judge the right tree.
28         if (!dfs4(root.right)) {
29             return false;
30         }
31
32         return true;
33     }

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/IsValidBST_1221_2014.java

时间: 2024-10-29 05:22:10

LeetCode: Validate Binary Search Tree 解题报告的相关文章

【LeetCode】Validate Binary Search Tree 解题报告

今天CSDN博客发生异常,折腾了大半天终于发出了这篇博文. [题目] 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

LeetCode: Recover Binary Search Tree 解题报告

Recover Binary Search Tree Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? c

[leetcode]Validate Binary Search Tree @ Python

原题地址:https://oj.leetcode.com/problems/validate-binary-search-tree/ 题意:检测一颗二叉树是否是二叉查找树. 解题思路:看到二叉树我们首先想到需要进行递归来解决问题.这道题递归的比较巧妙.让我们来看下面一棵树: 4 /    \ 2 6 /    \   /   \  1      3 5    7 对于这棵树而言,怎样进行递归呢?root.left这棵树的所有节点值都小于root,root.right这棵树的所有节点值都大于roo

LeetCode :: Validate Binary Search Tree[详细分析]

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 b

LeetCode: Validate Binary Search Tree [098]

[题目] 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

LeetCode: Lowest Common Ancestor of a Binary Search Tree 解题报告

https://leetcode.com/submissions/detail/32662938/ Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between t

【LeetCode】Recover Binary Search Tree 解题报告

[题目] Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? [解析] 题意:二叉搜索树中,有两个结点的位置

LeetCode: Convert Sorted Array to Binary Search Tree 解题报告

Convert Sorted Array to Binary Search Tree Given an array where elements are sorted in ascending order, convert it to a height balanced BST.SOLUTION 1:使用递归解决. base case: 当索引值超过时,返回null. 递归主体:构造根节点,调用递归构造左右子树.并将左右子树挂在根节点上. 返回值:返回构造的根节点. GITHUB: https:

LeetCode 700 Search in a Binary Search Tree 解题报告

题目要求 Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL. 题目分析及