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.

LeetCode: Validate Binary Search Tree  解题报告

SOLUTION 1:

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

算法思想:

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

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

LeetCode: Validate Binary Search Tree  解题报告

 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     }
View Code

相关文章: