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,505评论 0 10
  • ————《一切为心造》———— 快半个月过去了 自己似乎还没有适应 这漫长的假期生活 一方面不能按时作息,不早睡,...
    叶落菩提阅读 139评论 0 0
  • 明明应该是一个无忧无虑的年纪,但往往自己给自己施加压力。可能自己不会谈恋爱,也不知道该怎样去喜欢一个人,但就...
    过往云烟k阅读 405评论 17 1
  • 有多少年端午都没有在家过,有多少年没有吃到家乡的粽子了? 小的时候,端午节前奶奶就会带领着妈妈和姑妈...
    车前小草阅读 414评论 0 1
  • 幸福是不需要理由的,幸福是正常的,不幸福才是不正常的。 幸福是一种感觉,当你感觉幸福的时候就真的幸福。 幸福就像山...
    王思忠阅读 334评论 0 0