判斷是不是二叉搜尋樹——牛客網
阿新 • • 發佈:2022-05-30
描述
給定一個二叉樹根節點,請你判斷這棵樹是不是二叉搜尋樹。 二叉搜尋樹滿足每個節點的左子樹上的所有節點均嚴格小於當前節點且右子樹上的所有節點均嚴格大於當前節點。 例: 圖1 圖2 資料範圍:節點數量滿足 1 \le n\le 10^4 \1≤n≤104 ,節點上的值滿足 -2^{31} \le val \le 2^{31}-1\−231≤val≤231−1示例1
輸入:{1,2,3}返回值:
false說明:
如題面圖1
示例2
輸入:{2,1,3}返回值:
true說明:
如題面圖2
遞迴版
privateList<Integer> list = new ArrayList<>(); public boolean isValidBST (TreeNode root) { if (root == null) { return true; } boolean left = isValidBST(root.left); if (list.size() > 0 && root.val <= list.get(list.size() - 1)) { return false; } list.add(root.val);boolean right = isValidBST(root.right); return left && right; }
迭代版——棧模擬二叉樹中序遍歷
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public classSolution { /** * 程式碼中的類名、方法名、引數名已經指定,請勿修改,直接返回方法規定的值即可 * * * @param root TreeNode類 * @return bool布林型 * 迭代 */ public boolean isValidBST (TreeNode root) { // write code here Stack<TreeNode> stack = new Stack<>(); // 當前節點的前驅節點 TreeNode pre = null; while (!stack.isEmpty() || root != null) { // 1、一直走到當前樹的左邊界 while (root != null) { stack.push(root); root = root.left; } //2、取出棧頂元素,即當前樹的最左邊界節點,讓其跟前驅節點進行比較,即當前節點在中序遍歷得到的序列中是前驅節點的後繼節點 TreeNode pop = stack.pop(); if (pre != null && pre.val > pop.val) { return false; } // 3、將當前節點的右節點設定為根節點繼續重複第一個步驟(因為根據BST的定義:當前節點的右節點的值是比當前節點的父節點的值要小的) root = pop.right; // 4、將當前節點更新為前驅節點 pre = pop; } return true; } }
原題連結:https://www.nowcoder.com/practice/a69242b39baf45dea217815c7dedb52b?tpId=295&tqId=2288088&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj