zoukankan      html  css  js  c++  java
  • 二叉树最长距离

    tag: 二叉树

    思路:

    最长距离一定是两个叶子节点之间的距离

           => 两个叶子节点必定以某个节点为根节点

           => 因此用DFS思路自底向上计算经过每一个节点的最长距离,取其最大值

    以每个节点为根节点的最长距离 = 左子树的高度+右子树的高度

    package com.zhaochao.tree;
    
    /**
     * Created by zhaochao on 17/1/25.
     */
    public class MaxDistanceOfBT {
    
        int max = 0;
        public int maxDistance(TreeNode root) {
            if(root == null) {
                return 0;
            }
            if(root.left == null && root.right == null) {
                return 0;
            }
            //双枝
            max = Math.max(getHeight(root.left) + getHeight(root.right),max);
            //返回单枝
            return Math.max(getHeight(root.left),getHeight(root.right));
        }
    
    
        public int getHeight(TreeNode root) {
            if(root == null) {
                return 0;
            }
            int left = getHeight(root.left);
            int right = getHeight(root.right);
            return Math.max(left, right) + 1;
        }
    
        public static void main(String[] args) {
    
            TreeNode root = new TreeNode(0);
            TreeNode node1 = new TreeNode(1);
            TreeNode node2 = new TreeNode(2);
            TreeNode node3 = new TreeNode(3);
            TreeNode node4 = new TreeNode(3);
            TreeNode node5 = new TreeNode(3);
            TreeNode node6 = new TreeNode(3);
            TreeNode node7 = new TreeNode(3);
            TreeNode node8 = new TreeNode(3);
            TreeNode node9 = new TreeNode(3);
    
            root.left = node1;
            root.right = node2;
            node1.left = node3;
            node3.left = node8;
            node8.left = node9;
            node1.right = node5;
            node5.right = node6;
            node2.right = node4;
    
            MaxDistanceOfBT test = new MaxDistanceOfBT();
    
            test.maxDistance(root);
            System.out.println(test.max);
    
        }
    
    }
    

      

  • 相关阅读:
    仿12306客户端
    object-c开发中混合使用或不使用ARC
    Objective-c 的 @property 详解
    iPhone的Push(推送通知)功能原理浅析
    Objective-C内存管理教程和原理剖析3
    IDEA 创建JAVA Maven Web 工程
    Linux CenOS 7 安装Redis
    Linux CenOS 7 安装Tomcat
    Linux CentOS 7 安装wordpress
    Linux CenOS 7 安装JDK
  • 原文地址:https://www.cnblogs.com/superzhaochao/p/6351230.html
Copyright © 2011-2022 走看看