二叉樹的最大直徑

543. Diameter of Binary Tree
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of thelongest path between any two nodes in a tree. This path may or may not pass through the root.

Example:
Given a binary tree 

          1
         / \
        2   3
       / \     
      4   5    
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note:The length of path between two nodes is represented by the number of edges between them.

二叉樹的直徑:二叉樹中從一個結點到另一個節點最長的路徑,叫做二叉樹的直徑
採用分治和遞歸的思想:根節點爲root的二叉樹的直徑 = Max(左子樹直徑,右子樹直徑,左子樹的最大深度(不包括根節點)+右子樹的最大深度(不包括根節點)+1)
 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
 
	// 全局變量,記錄最大直徑
	int diameter = 0;
 
	public int diameterOfBinaryTree(TreeNode root) {
		getDepth(root);
		return diameter;
	}
 
	// 此函數是返回樹的最大深度
	private int getDepth(TreeNode root) {
		if (root == null)
			return 0;
		int l = getDepth(root.left);
		int r = getDepth(root.right);
		diameter = Math.max(diameter, l + r);
		return Math.max(l, r) + 1;
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章