zoukankan      html  css  js  c++  java
  • 《程序员代码面试指南》第三章 二叉树问题 找到二叉树中最大搜索二叉树

    题目

    找到二叉树中最大搜索二叉树
    

    java代码

    package com.lizhouwei.chapter3;
    
    /**
     * @Description:找到二叉树中最大搜索二叉树
     * @Author: lizhouwei
     * @CreateDate: 2018/4/14 20:39
     * @Modify by:
     * @ModifyDate:
     */
    public class Chapter3_7 {
        public Node biggestSubBST(Node head) {
            int[] record = new int[3];
            return postOrder(head, record);
        }
    
        public Node postOrder(Node head, int[] record) {
            if (head == null) {
                record[0] = 0;
                record[1] = Integer.MAX_VALUE;//子树最小值
                record[2] = Integer.MIN_VALUE;//子树最大值
                return null;
            }
            int value = head.value;
            Node left = postOrder(head.left, record);
            int leftSize = record[0];
            int leftMin = record[1];
            int leftMax = record[2];
            Node right = postOrder(head.right, record);
            int rightSize = record[0];
            int rightMin = record[1];
            int rightMax = record[2];
            record[1] = Math.min(leftMin, value);
            record[2] = Math.max(rightMax, value);
            if (left == head.left && right == head.right && leftMax < value && value < rightMin) {
                record[0] = leftSize + rightSize + 1;
                return head;
            }
            record[0] = Math.max(leftSize, rightSize);
            return leftSize > rightSize ? left : right;
        }
    
        //测试
        public static void main(String[] args) {
            Chapter3_7 chapter = new Chapter3_7();
            Node head = new Node(6);
            head.left = new Node(1);
            head.right = new Node(12);
            head.left.left = new Node(0);
            head.left.right = new Node(3);
    
            head.right.left = new Node(10);
            head.right.right = new Node(13);
    
            head.right.left.left = new Node(4);
            head.right.left.right = new Node(14);
            head.right.right.left = new Node(20);
            head.right.right.right = new Node(16);
    
            head.right.left.left.left = new Node(2);
            head.right.left.left.right = new Node(5);
            head.right.left.right.left = new Node(11);
            head.right.left.right.right = new Node(15);
            Node subHead = chapter.biggestSubBST(head);
            NodeUtil.inOrder(subHead);
        }
    }
    
    
  • 相关阅读:
    HDU 1078 FatMouse and Cheese (简单DP)
    HDU 1052 Tian Ji The Horse Racing (贪心)
    HDU 4432 Sum of divisors 第37届ACM/ICPC天津现场赛B题 (简单题)
    HDU 1079 Calendar Game (博弈)
    HDU 4438 Hunters 第37届ACM/ICPC 天津赛区现场赛H题(超级水的题目)
    php级联
    C++运算符重载
    C++循环语句
    C++类复制构造函数
    C++ struct,union和enum
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8835840.html
Copyright © 2011-2022 走看看