zoukankan      html  css  js  c++  java
  • 给定一棵二叉树,已经其中没有重复值的节点,请判断该二叉树是否为搜索二叉树和完全二叉树。

    判断是否是二叉搜索树
    通过取值范围判断,递归过程中判断;

    判断是否是完全二叉树。

    通过一个层次遍历判断,具体思路是:

    遍历过程中,第一次遇到了空节点,则需要通过标记记录。

    只要非空,就要判断前面是否出现了空(标记记录); 出现了空,则不是完全二叉树; 同时将两个子节点入队(不管是否为空都行);

    完全二叉树的队列中的元素应该是(包含空的儿子也入队的话): 非空, 非空, 非空, 非空, 非空, 空,空,空,空,空

    import java.util.*;
    
    /*
     * public class TreeNode {
     *   int val = 0;
     *   TreeNode left = null;
     *   TreeNode right = null;
     * }
     */
    
    public class Solution {
        /**
         * 
         * @param root TreeNode类 the root
         * @return bool布尔型一维数组
         */
        boolean flag1 = true;
        boolean flag2 = true;
        public boolean[] judgeIt (TreeNode root) {
            // write code here
            boolean[] ans = new boolean[2];
            inorder(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
            ans[0] = flag1;
            
            ans[1] = func(root);
            return ans;
        }
        public void inorder(TreeNode root, int start, int end){
            if(flag1 == false) return;
            if(root == null)
                return;
            if(root.val < start || root.val >end){
                flag1 = false;
                return;
            }
            
            inorder(root.left, start, root.val);
            inorder(root.right, root.val, end);
        }
        
        public boolean func(TreeNode root){
            if(root == null)
                return false;
            Queue<TreeNode> queue = new LinkedList<TreeNode> ();
            if(root != null){
                queue.add(root);
            }
            boolean flag = false;
            while(!queue.isEmpty()){
                TreeNode node = queue.poll();
                if(node != null){
                    if(flag == true){
                        return false;
                    }
                    queue.add(node.left);
                    queue.add(node.right);
                } else {
                    // 第一次遇到空的时候做一下标记
                    if(flag == false){
                        flag = true;
                    }
                }
            }
            return true;
        }
    }
    
  • 相关阅读:
    shell脚本比较字符串相等
    从自身的经历讨论手工测试与自动化测试
    读《Linux Shell脚本攻略》(第2版) 一遍、二遍体会
    也许开发需要的只是一份简单明了的表格
    linux 命令:tr 的简单使用
    docker的数据持久化
    docker基础操作
    centos7 docker镜像源设置
    DockerUI(图形化管理)
    Docker 常用命令
  • 原文地址:https://www.cnblogs.com/sidewinder/p/13751560.html
Copyright © 2011-2022 走看看