二叉树最长距离
Posted notesbuddy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树最长距离相关的知识,希望对你有一定的参考价值。
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); } }
以上是关于二叉树最长距离的主要内容,如果未能解决你的问题,请参考以下文章
NC41 最长无重复子数组/NC133链表的奇偶重排/NC116把数字翻译成字符串/NC135 股票交易的最大收益/NC126换钱的最少货币数/NC45实现二叉树先序,中序和后序遍历(递归)(代码片段