首页 > 代码库 > 二叉树最长距离
二叉树最长距离
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); } }
二叉树最长距离
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。