LeetCode543. Diameter of Binary Tree

Solution1

If we think about it, there may be three conditions for the largest diameter of a binary tree.

  1. The largest diamater exists in the left subtree of the root.
  2. The largest diameter exits in the right subtree of the root.
  3. The largest diameter exists and contains the root, that is, the corresponding path of the largest diameter extends from left subtree, including root, to right subtree.

And considering the property of a binary tree, these conditions can be applied to every node in the tree. Thus we can write a helper function to deal with this question. For every node, we will return 3 values to its parent: left subtree's max depth, right subtree's max length, and max diameter of current tree rooted at this node.

For each tree node, max left depth, max right depth, max diameter could be calculated as following respectively:

  1. max_left_depth = max(left_subtree's max_left depth, left subtree's max_right_depth) + 1
  2. max_right_depth = max(right_subtree's max_left depth, right subtree's max_right_depth) + 1
  3. max_diameter = max(left_subtree's max_diameter, right_subtree's max_diameter, max_left_subtree_depth + max_right_subtree_depth + 1)

As a result, for the root node, we just need to return the 3rd value we get since this records the maximum diameter for the whole tree. However, since the actual definition of the diameter is the number of edges, we simply deduct 1 from the value we get, which is the number of nodes in the longest diameter.

Suppose there are n nodes in the tree, this algorithm runs in O(logn) time and O(1) space without considering the recursion stack.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int diameterOfBinaryTree(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int ret[] = diameterHelper(root);
        return ret[2] - 1;
    }
    
    private int[] diameterHelper(TreeNode curr) {
        if (curr == null) return new int[]{0, 0, 0};
        
        // [max depth of left subtree, max depth of right subtree, max diameter of left-curr-right subtree]
        int[] ret = new int[3];
        int[] leftRet = diameterHelper(curr.left);
        int[] rightRet = diameterHelper(curr.right);
        ret[0] = Math.max(leftRet[0], leftRet[1]) + 1;
        ret[1] = Math.max(rightRet[0], rightRet[1]) + 1;
        int maxDiameter = Math.max(leftRet[0], leftRet[1]) + Math.max(rightRet[0], rightRet[1]) + 1;
        maxDiameter = Math.max(maxDiameter, leftRet[2]);
        maxDiameter = Math.max(maxDiameter, rightRet[2]);
        ret[2] = maxDiameter;
        
        return ret;
    }
}

Solution2

However, from the above solution, it can be seen that the actual longest diameter for every node is just the max_left_depth + max_right_depth. Hence we could use a global max value to keep track of the largest diameter to make the code clean.

class Solution {
    int max = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        diameterHelper(root);
        return max;
    }
    
    private int diameterHelper(TreeNode root) {
        if (root == null) return 0;
        
        int leftDep = diameterHelper(root.left);
        int rightDep = diameterHelper(root.right);
        max = Math.max(max, leftDep + rightDep);
        return Math.max(leftDep, rightDep) + 1;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,769評論 0 33
  • 姥姥,你還好嗎?昨天夜里,我又夢到你了,夢到你和姥爺在天堂里坐在一起曬著太陽,夢到你和姥爺樂呵呵地笑著,我知道,你...
    梅花映雪閱讀 445評論 9 6
  • 最近身邊很多人都說:“楊紫越變越美了。”是啊,《家有兒女》里的童星都長大了,女大十八變,她早已經不是我們記憶中的小...
    潮流一起說閱讀 447評論 0 0
  • 圣誕節就要到了,我又想起了紅鼻子鹿魯道夫的故事。魯道夫因為它的紅鼻子而被人嘲笑,也因為它的紅鼻子成為了圣誕老...
    吳恩澤閱讀 738評論 0 0
  • 感覺最近的雨就像憋壞的膀胱,怎么尿都尿不盡。在這樣一個濕嗒嗒的季節,小編開始蠢蠢欲動起來。這次我們玩把大的。果照曬...
    愛叮叮閱讀 513評論 0 1