zoukankan      html  css  js  c++  java
  • Validate Binary Search Tree(一定掌握的方法)

    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.

    这题使用迭代的中序遍历。中序遍历是遍历左中右节点,所以对于二叉搜索树,后一个节点肯定比上一个节点大。所以根据这个思路,假设一个节点pre表示前一个节点,如果下一个节点比pre小,就返回false。中序遍历从最左边的子树开始遍历的,pre一开始就是null。当左中右遍历完,pre 在右子树上,这样继续上一层(中间的父节点)也是比pre大。

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean isValidBST(TreeNode root) {
            if(root==null) return true;
            Stack<TreeNode> stack=new Stack<>();
            TreeNode pre=null;
            while(root!=null||!stack.isEmpty()){
                if(root!=null){  //将左节点依次存进栈,存完后开始遍历
                    stack.add(root);
                    root=root.left;
                }else{
                    root=stack.pop();
                    if(pre!=null&&root.val<=pre.val) return false;
                    pre=root;
                    root=root.right;
                }
            }
            return true;
        }
    }

    下面是Binary Tree Inorder Traversal ,中序遍历二叉树非递归方法。

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null) return list;
        Stack<TreeNode> stack = new Stack<>();
        while(root != null || !stack.empty()){
            if(root != null){
                stack.push(root);
                root = root.left;
            }else{
            root = stack.pop();
            list.add(root.val);
            root = root.right;
            }
        }
        return list;
    }
  • 相关阅读:
    ES6 数值
    ES6 字符串
    ES6 Reflect 与 Proxy
    ES6 Map 与 Set
    es6 Symbol
    新兴的API(fileReader、geolocation、web计时、web worker)
    浏览器数据库 IndexedDB 入门教程
    离线应用与客户端存储(cookie storage indexedDB)
    javascript高级技巧篇(作用域安全、防篡改、惰性载入、节流、自定义事件,拖放)
    ajax与comet
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8257428.html
Copyright © 2011-2022 走看看