zoukankan      html  css  js  c++  java
  • 《程序员代码面试指南》第三章 二叉树问题 判断二叉树是否为搜素二叉树

    题目

    判断二叉树是否为搜素二叉树
    

    java代码

    package com.lizhouwei.chapter3;
    
    /**
     * @Description:判断二叉树是否为搜素二叉树
     * @Author: lizhouwei
     * @CreateDate: 2018/4/14 23:10
     * @Modify by:
     * @ModifyDate:
     */
    public class Chapter3_13 {
        public boolean isBalance(Node head) {
            if (head == null) {
                return false;
            }
            boolean[] record = new boolean[1];
            record[0] = true;
            getHight(head, 1, record);
            return record[0];
        }
    
        public int getHight(Node head, int level, boolean[] record) {
            if (head == null) {
                return level;
            }
            int leftDep = getHight(head.left, level + 1, record);
            if (!record[0]) {
                return level;
            }
            int rightDep = getHight(head.right, level + 1, record);
            if (!record[0]) {
                return level;
            }
            if (Math.abs(rightDep - leftDep) > 1) {
                record[0] = false;
            }
            return Math.max(leftDep, rightDep);
        }
    
        //测试
        public static void main(String[] args) {
            Chapter3_13 chapter = new Chapter3_13();
            Node head = new Node(1);
            head.left = new Node(2);
            head.right = new Node(3);
            head.left.left = new Node(4);
            head.left.right = new Node(5);
            head.left.left.left = new Node(8);
            head.left.left.right = new Node(9);
            head.left.right.left = new Node(10);
    
            System.out.print("head是否为平衡树 :" + chapter.isBalance(head));
            System.out.println();
            Node head2 = new Node(1);
            head2.left = new Node(2);
            head2.right = new Node(3);
            head2.left.left = new Node(4);
            head2.left.right = new Node(5);
            head2.right.left = new Node(6);
            head2.right.right = new Node(7);
            System.out.print("head2是否为平衡树 :" + chapter.isBalance(head2));
        }
    
    }
    

    结果

  • 相关阅读:
    hdu 4027 Can you answer these queries?
    hdu 4041 Eliminate Witches!
    hdu 4036 Rolling Hongshu
    pku 2828 Buy Tickets
    hdu 4016 Magic Bitwise And Operation
    pku2886 Who Gets the Most Candies?(线段树+反素数打表)
    hdu 4039 The Social Network
    hdu 4023 Game
    苹果官方指南:Cocoa框架(2)(非原创)
    cocos2d 中 CCNode and CCAction
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8836822.html
Copyright © 2011-2022 走看看