zoukankan      html  css  js  c++  java
  • 104. Maximum Depth of Binary Tree

    104. Maximum Depth of Binary Tree
    Easy

    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.

     对于给定的1个结点,如果不为空,那么depth就为1。

    然后需要遍历左右子结点,分别得到depth,并且取其中较大的值。

    只要左右子结点,有一个不为空,那就递归遍历。

    public int MaxDepth(TreeNode root)
            {
                int depth;
                if (root == null)
                {
                    depth = 0;
                }
                else
                {
                    depth = 1;
                    TreeNode left = root.left;
                    TreeNode right = root.right;
                    if (left != null || right != null)
                    {
                        int leftDepth = MaxDepth(left);
                        int rightDepth = MaxDepth(right);
                        depth = depth + Math.Max(leftDepth, rightDepth);
                    }
                }
    
                return depth;
            }
  • 相关阅读:
    学习进度16
    个人总结
    人月神话阅读笔记09
    人月神话阅读笔记08
    人月神话阅读笔记07
    构建之法阅读笔记06
    构建之法阅读笔记05
    构建之法阅读笔记04
    构建之阅读笔记03
    Python安装 pip 和 easy_install
  • 原文地址:https://www.cnblogs.com/chucklu/p/10551598.html
Copyright © 2011-2022 走看看