leetcode543. 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 the longest path between any two nodes in a tree. This path may or may not pass through the root.java

Example:
Given a binary treenode

1
     / \
    2   3
   / \   
  4   5

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

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

二叉樹的直徑是指從一個葉節點到另外一個葉節點的最遠距離,而這個距離是指兩個節點之間的路徑長,注意,這條路徑不必定通過根節點。class

思路和代碼

這裏能夠經過遞歸來完成計算,經過先遞歸的計算出左子樹的最大高度,再遞歸的計算出右子樹的最大高度,就能夠得出當前節點能夠構成的最長路徑。須要將該值記錄下來。再遞歸的返回該節點的最大高度給外層調用方運用。二叉樹

int max = 0;  
public int diameterOfBinaryTree(TreeNode root) {  
    heightOfBinaryTree(root);  
    return max;  
}  
  
public int heightOfBinaryTree(TreeNode root) {  
    if (root == null) {  
        return 0;  
    }  
    int left = heightOfBinaryTree(root.left);  
    int right = heightOfBinaryTree(root.right);  
    max = Math.max(left + right + 1, max);  
    return Math.max(left, right) + 1;  
}
相關文章
相關標籤/搜索