標籤:nbsp 需要 int 編程 else arch 子節點 boolean 理論
題目:
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.
Example 1:
2 / 1 3
Binary tree [2,1,3], return true.
Example 2:
1 / 2 3
Binary tree [1,2,3], return false.
題意及分析:給出一課書,要求判斷該樹是不是二叉搜尋樹。二叉搜尋樹按照中序遍曆得到的是一個升序序列,那麼這道題只需要對樹進行中序遍曆即可,使用stack儲存中間結果。這裡需要注意的是理論最小值的擷取,這裡先擷取最小值,然後當遍曆到這個點時不需要做判斷。
代碼:
/** * 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; //找到理論的最小值點 Stack<TreeNode> stack = new Stack<>(); TreeNode node = root; stack.add(node); while(node.left!=null||!stack.isEmpty()){ if(node.left!=null){ //一直找到最左子節點 node = node.left; stack.add(node); }else{ //輸出該點,對棧當前點的右節點做相同操作 TreeNode now = stack.pop(); if(now!=minNode){ if(now.val>nowMax){ //如果當前大於遍曆的上一個那麼當前最大值編程當前點最大值 nowMax = now.val; }else{ //按照中序遍曆輸出,結果當前輸出比上一個數小,那麼直接返回false return false; } } if(now.right!=null) { node = now.right; stack.add(node); //將當前點加入stack中 } } } return true; }}
[LeetCode] 98. Validate Binary Search Tree Java