zoukankan      html  css  js  c++  java
  • 验证二叉查找树(LintCode) .

    验证二叉查找树

    给定一个二叉树,判断它是否是合法的二叉查找树(BST)

    一棵BST定义为:

    • 节点的左子树中的值要严格小于该节点的值。
    • 节点的右子树中的值要严格大于该节点的值。
    • 左右子树也必须是二叉查找树。
    样例

    一个例子:

      2
     / \
    1   4
       / \
      3   5
    

    上述这棵二叉树序列化为 {2,1,4,#,#,3,5}.

    中序遍历得到中序遍历序列,验证是否递增即可。

     1 /**
     2  * Definition of TreeNode:
     3  * public class TreeNode {
     4  *     public int val;
     5  *     public TreeNode left, right;
     6  *     public TreeNode(int val) {
     7  *         this.val = val;
     8  *         this.left = this.right = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     /**
    14      * @param root: The root of binary tree.
    15      * @return: True if the binary tree is BST, or false
    16      */
    17      
    18     public boolean isValidBST(TreeNode root) {
    19         List<Integer> list = new ArrayList<Integer>();
    20         midOrder(root,list);
    21         for(int i=1;i<list.size();i++) {
    22             if(list.get(i-1) >= list.get(i))return false;
    23         }
    24         
    25         return true;
    26     }
    27     
    28     public void midOrder(TreeNode root,List<Integer> list) {
    29         if(root == null) return;
    30         midOrder(root.left,list);
    31         list.add(root.val);
    32         midOrder(root.right,list);
    33     }
    34 }
    View Code
  • 相关阅读:
    10多媒体
    胡凡-01
    概念
    算法
    07Axios
    05VueCli
    04Vue.js路由系统
    03生命周期
    《穷人思维》学习感悟
    《基金》学习感悟之二
  • 原文地址:https://www.cnblogs.com/FJH1994/p/5025622.html
Copyright © 2011-2022 走看看