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.
判斷一個樹是不是二叉查找樹。二叉查找樹即知足當前節點左子樹的值均小於當前節點的值,右子樹的值均大於當前節點的值。node
能夠看到,對二叉查找樹的中序遍歷結果應當是一個遞增的數組。這裏咱們用堆棧的方式實現中序遍歷。面試
public boolean isValidBST(TreeNode root) { long currentVal = Long.MIN_VALUE; LinkedList<TreeNode> stack = new LinkedList<TreeNode>(); while(root!=null || !stack.isEmpty()){ while(root!=null){ stack.push(root); root = root.left; } root = stack.pop(); if(root.val<=currentVal) return false; currentVal = root.val; root = root.right; } return true; }
咱們能夠發現,若是已知當前節點的值val以及取值的上下限upper,lower,那麼左子節點的取值範圍就是(lower, val),右子節點的取值範圍就是(val, upper)。由此出發遞歸判斷,時間複雜度爲O(n)由於每一個節點只須要遍歷一次。數組
public boolean isValidBST2(TreeNode root){ return isValid(root, Long.MIN_VALUE, Long.MAX_VALUE); } public boolean isValid(TreeNode treeNode, long lowerBound, long upperBound){ if(treeNode==null) return true; if(treeNode.val>=upperBound || treeNode.val<=lowerBound) return false; return isValid(treeNode.left, lowerBound,treeNode.val) && isValid(treeNode.right, treeNode.val, upperBound); }
想要了解更多開發技術,面試教程以及互聯網公司內推,歡迎關注個人微信公衆號!將會不按期的發放福利哦~微信