[LeetCode] 98. Validate Binary Search Tree Java

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.