1、題目描述
????給定一棵二叉樹,計算這課二叉樹的直徑長度,即為二叉樹任意兩個節點間的最長路徑。比如:
????????
? ? ?這棵二叉樹的最長路徑為3。
2、解題思路
????使用遞歸進行求解,每次遞歸的過程中,先求出以某個節點為樹根的二叉樹的左子樹的最長深度maxLeft、右子樹的最長深度maxRight,并在遞歸函數中用一個變量maxLen來保存任意兩個節點間的最長路徑。在求出左子樹的最長深度maxLeft和右子樹的最長深度maxRight之后,就可以求出以該節點為根的二叉樹的最長路徑maxLen。具體代碼如下:
public class Solution {static int maxLen = 0;public static void main(String[] args) {TreeNode root = new TreeNode(0);TreeNode p1 = new TreeNode(1);TreeNode p2 = new TreeNode(2);TreeNode p3 = new TreeNode(3);TreeNode p4 = new TreeNode(4);TreeNode p5 = new TreeNode(5);TreeNode p6 = new TreeNode(6);TreeNode p7 = new TreeNode(7);TreeNode p8 = new TreeNode(8);root.left = p1;root.right = p2;p1.left = p3;p3.left = p4;p2.left = p5;p2.right = p6;p6.right = p7;p7.right = p8;FindMaxLen(root);System.out.println(maxLen);}public static void FindMaxLen(TreeNode pRoot) {if (pRoot == null) {// 空的話直接結束return;}if (pRoot.left == null) {// 左子為空,左面最大長度為0pRoot.maxLeft = 0;}if (pRoot.right == null) {// 右子為空,右面最大長度為0pRoot.maxRight = 0;}if (pRoot.left != null) {// 遞歸獲取以左子節點為根節點的最大距離FindMaxLen(pRoot.left);}if (pRoot.right != null) {// 遞歸獲取以右子節點為根節點的最大距離FindMaxLen(pRoot.right);}if (pRoot.left != null) {// 左面最大距離=左子左面最大距離與左子右面最大距離取最大值+1pRoot.maxLeft = Math.max(pRoot.left.maxLeft, pRoot.left.maxRight) + 1;}if (pRoot.right != null) {// 右面最大距離=右子左面最大距離與右子右面最大距離取最大值+1pRoot.maxRight = Math.max(pRoot.right.maxLeft, pRoot.right.maxRight) + 1;}if (pRoot.maxLeft + pRoot.maxRight > maxLen) {// 刷新最大距離maxLen = pRoot.maxLeft + pRoot.maxRight;}}}class TreeNode {TreeNode left;TreeNode right;int maxLeft;int maxRight;int data;public TreeNode(int data) {this.data = data;}
}
3、另一種解法:遞歸
public static int FindMaxLen(TreeNode pRoot) {if (pRoot == null) {return 0;}// 遞歸獲取左子、右子的最大距離int maxLeft = FindMaxLen1(pRoot.left);int maxRight = FindMaxLen1(pRoot.right);// 刷新最大距離maxLen = Math.max(maxLeft + maxRight, maxLen);// 返回該節點的父節點在該側的最大距離return Math.max(maxLeft, maxRight) + 1;
}
?