Topic:
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 is binary search trees.
Example 1:
2 / 1 3
Binary Tree [2,1,3]
, return True.
Example 2:
1 / 2 3
Binary tree [1,2,3]
, return false.
test instructions and analysis: give a lesson about whether the tree is a binary search tree. Binary search tree According to the middle order traversal is an ascending sequence, then this problem only need to carry out a sequential traversal of the tree, using the stack to save the intermediate results. It is important to note that the theoretical minimum is obtained, where the minimum value is obtained first, and then no judgment is required when traversing to this point.
Code:
/** * Definition for a binary tree node. * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution {public Boolean isvalidbst (TreeNode root) {if (root==null| | (Root.left==null&&root.right==null)) return true; TreeNode Minnode = root; while (minnode.left!=null) {minnode=minnode.left; } long Nowmax=minnode.val; Find the minimum point of the theory stack<treenode> Stack = new stack<> (); TreeNode node = root; Stack.add (node); while (node.left!=null| |! Stack.isempty ()) {if (node.left!=null) {//always finds the leftmost child node = Node.left; Stack.add (node); }else{//Outputs the point, doing the same operation on the right node of the current point of the stack TreeNode now = Stack.pop (); if (Now!=minnode) {if (Now.val>nowmax) {///If the current maximum value is currently greater than the previous iteration of the Traverse, the current max value is Nowmax = Now.val; }else{//In accordance with the middle sequence of the output, the results of the current output is smaller than the previous number, then directly return false return to false; }} if (Now.right!=null) {node = now.right; Stack.add (node); Add the current point to the Stack}}} and return true; }}
[Leetcode] 98. Validate Binary Search Tree Java