有效二叉查找樹判斷(java實現)

leetcode 原題 :(即判斷二叉樹是否爲二叉查找樹)java

Given a binary tree, determine if it is a valid binary search tree (BST).node

Assume a BST is defined as follows:less

  • 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

下面採用java實現:spa

public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
      TreeNode(int x) { val = x; }
  }
 
public class ValidateBST{
    boolean flag=true;
    TreeNode pre=null;//保存前驅節點
    public boolean isValidBST(TreeNode root) {
         dfs(root);
         return flag;
    }
  //採用中序遍歷,若是前節點不小於當前節點的值,則不符合BST的條件
private void dfs(TreeNode root){ if(root!=null){ dfs(root.left); if(pre!=null&&root.val<=pre.val)flag= false; pre=root; dfs(root.right); } }}
相關文章
相關標籤/搜索