104 Maximum Depth Of Binary Tree


title: Maximum Depth Of Binary Tree
tags:
- maximum-depth-of-binary-tree
- No.104
- simple
- tree
- depth-first-search
- breadth-first-search
- recurrence
- stack
- queue


Description

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

Corner Cases

  • empty tree

Solutions

Post-Order Depth First Search

It's obvious that for any node a, the height of a, h(a) have:

h(a) = max{h(a.left), h(a.right)} + 1

Running time is O(V+E).

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        return h(root);
    }
    
    private int h(TreeNode a) {
        if (a == null) {return 0;}
        int hleft  = h(a.left);
        int hright = h(a.right);
        return (hleft > hright) ? hleft + 1 : hright + 1;
    }
}

Stack Without Recurrence

Note that we must not pop the parent untill left and right children heights are computed, which makes it a post-order dfs. Only in this case, the terms in the stack would be all the parents of the current node. And thus the depth or height is the size of the stack.

In stack post-dfs, the right child is pushed into the stack before left child so that left first right second when being poped.

Maintain the property: the current node is the first element of the stack.


Breadth First Search

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,434評論 0 10
  • ————《一切為心造》———— 快半個月過去了 自己似乎還沒有適應 這漫長的假期生活 一方面不能按時作息,不早睡,...
    葉落菩提閱讀 136評論 0 0
  • 明明應該是一個無憂無慮的年紀,但往往自己給自己施加壓力??赡茏约翰粫剳賽?,也不知道該怎樣去喜歡一個人,但就...
    過往云煙k閱讀 402評論 17 1
  • 有多少年端午都沒有在家過,有多少年沒有吃到家鄉的粽子了? 小的時候,端午節前奶奶就會帶領著媽媽和姑媽...
    車前小草閱讀 405評論 0 1
  • 幸福是不需要理由的,幸福是正常的,不幸福才是不正常的。 幸福是一種感覺,當你感覺幸福的時候就真的幸福。 幸福就像山...
    王思忠閱讀 311評論 0 0