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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

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

友情鏈接更多精彩內(nèi)容