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)系作者
  • 序言:七十年代末丹莲,一起剝皮案震驚了整個濱河市慎恒,隨后出現(xiàn)的幾起案子感昼,更是在濱河造成了極大的恐慌辟宗,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,919評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件县踢,死亡現(xiàn)場離奇詭異即寡,居然都是意外死亡,警方通過查閱死者的電腦和手機笛钝,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,567評論 3 392
  • 文/潘曉璐 我一進店門质况,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人玻靡,你說我怎么就攤上這事结榄。” “怎么了囤捻?”我有些...
    開封第一講書人閱讀 163,316評論 0 353
  • 文/不壞的土叔 我叫張陵臼朗,是天一觀的道長。 經(jīng)常有香客問我蝎土,道長视哑,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,294評論 1 292
  • 正文 為了忘掉前任誊涯,我火速辦了婚禮挡毅,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘暴构。我一直安慰自己慷嗜,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,318評論 6 390
  • 文/花漫 我一把揭開白布丹壕。 她就那樣靜靜地躺著,像睡著了一般薇溃。 火紅的嫁衣襯著肌膚如雪菌赖。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,245評論 1 299
  • 那天沐序,我揣著相機與錄音琉用,去河邊找鬼。 笑死策幼,一個胖子當(dāng)著我的面吹牛邑时,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播特姐,決...
    沈念sama閱讀 40,120評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼晶丘,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起浅浮,我...
    開封第一講書人閱讀 38,964評論 0 275
  • 序言:老撾萬榮一對情侶失蹤沫浆,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后滚秩,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體专执,經(jīng)...
    沈念sama閱讀 45,376評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,592評論 2 333
  • 正文 我和宋清朗相戀三年郁油,在試婚紗的時候發(fā)現(xiàn)自己被綠了本股。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,764評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡桐腌,死狀恐怖拄显,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情哩掺,我是刑警寧澤凿叠,帶...
    沈念sama閱讀 35,460評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站嚼吞,受9級特大地震影響盒件,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜舱禽,卻給世界環(huán)境...
    茶點故事閱讀 41,070評論 3 327
  • 文/蒙蒙 一炒刁、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧誊稚,春花似錦翔始、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,697評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至疾瓮,卻和暖如春脖镀,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背狼电。 一陣腳步聲響...
    開封第一講書人閱讀 32,846評論 1 269
  • 我被黑心中介騙來泰國打工蜒灰, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人肩碟。 一個月前我還...
    沈念sama閱讀 47,819評論 2 370
  • 正文 我出身青樓强窖,卻偏偏與公主長得像,于是被迫代替她去往敵國和親削祈。 傳聞我的和親對象是個殘疾皇子翅溺,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,665評論 2 354

推薦閱讀更多精彩內(nèi)容

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