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);
        }
    }
    
    
  • 相关阅读:
    新概念4-16
    答疑汇总-02
    理解Marx-8 9 10晚年的思考 马恩关系再认识 一段思想史的公案
    nefu 116
    nefu 115
    【JZOJ3379】查询【主席树】
    【JZOJ1782】Travel【分层图最短路】
    【洛谷P4550】收集邮票【期望概率】
    【洛谷P1001】A+B Problem
    【JZOJ3339】wyl8899和法法塔的游戏【暴力】
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8835840.html
Copyright © 2011-2022 走看看