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;
    }
  • 相关阅读:
    Nginx学习高可用
    Nginx安装学习
    Nginx服务器熟悉
    SVN无法连接解决方法
    CentOS 7下搭建SVN服务器&多项目教程
    iframe操作
    Java 微服务架构选型
    vue-cli4.5创建vue项目
    线程间的协作(wait/notify/sleep/yield/join)
    多线程的创建、停止
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8257428.html
Copyright © 2011-2022 走看看