zoukankan      html  css  js  c++  java
  • 【LeetCode练习题】Maximum Depth of Binary Tree

    Maximum Depth of Binary Tree

    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.

    求二叉树的高度,即从根节点到叶节点上所有节点的数量。

    解题思路:

    这题是难度系数1,频率1的题目……用到的知识点是二叉树DFS(深度遍历)。

    一个计数变量count,一个记录最大值变量max。

    深度遍历的时候,遍历到的节点分三种情况:

    1. 叶节点。此时比较max和count的大小,将较大的那个赋值给max。
    2. 非叶节点,且有左节点无右节点,继续遍历其左节点,从左节点返回时要将count减1. 右节点不遍历了。
    3. 非叶节点,且有右节点无左节点,继续遍历其右节点,从右节点返回时要将count减1. 左节点不便利了。

    max即为所求的最大深度。

    代码如下:

    class Solution {
    public:
        int maxDepth(TreeNode *root) {
            int count = 0,max = 0;
            depth(root,count,max);
            return max;
        }
        
        void depth(TreeNode *root,int &count,int &max){
            if(root){
                if(!root->left && !root->right){
                    count++;
                    if(max < count)
                        max = count;
                }
                else{
                    count++;
                    if(root->left){
                        depth(root->left,count,max);
                        count--;
                    }
                    if(root->right){
                        depth(root->right,count,max);
                        count--;
                    }
                }
            }
        }
    };

     难怪难度系数是1,可以简单成这个样子:

    class Solution {  
    public:  
        int maxDepth(TreeNode *root) {  
            if(root == NULL) return 0;  
              
            int l = maxDepth(root->left);  
            int r = maxDepth(root->right);  
              
            return l > r ? l + 1 : r + 1;  
        }  
    }; 
  • 相关阅读:
    一个项目需要提交哪了些文档?
    aspose.cells
    国内人才申领《上海市居住证》审核试行办法
    SPRING.NET 1.3.2 学习1组件功能说明
    Nhibernate中实现多数据库支持
    Asp.net Mvc 实用技巧
    windwos server 2008 r2安装,一些最基本设置需要注意的地方
    配置SQL Server的身份验证方式
    MindManager 2012 简介(安装)
    Git 管理篇章
  • 原文地址:https://www.cnblogs.com/4everlove/p/3662343.html
Copyright © 2011-2022 走看看