Leetcode-Validate Binary Search Tree
Description:
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 '# 'signiies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5
The above binary tree is serialized"{1,2,3,#,#,4,#,#,5}"
.
Ideas:Because the Binary Tree and the value generated by the central traversal of a binary tree are ordered and necessary, you only need to perform the central traversal of the binary tree, store the value of the traversal node to a list, and compare the values in the list in sequence. If it is ordered, the binary tree is a binary sorting tree; otherwise, it is not.
Of course, a better way is to use a temp to store the value of the previous node, and then compare it in sequence.
Code:
public boolean isValidBST(TreeNode root) {boolean flag=true;List
list=new ArrayList
(); if(root==null) return flag; Stack
st=new Stack
(); st.push(root); TreeNode top=null; while(!st.empty()) { top=st.peek(); while(top.left!=null) { st.push(top.left); top=top.left; } while(top.right==null) { list.add(top.val); st.pop(); if(!st.empty()) top=st.peek(); else break; } if(!st.empty()) { list.add(top.val); st.pop(); st.push(top.right); } } int len=list.size(); int num=list.get(0),temp=0; for(int i=1;i
temp) { flag=false; break; } num=temp; }return flag; }
Result: