首页 > 其他 > 详细

Maximum Depth of Binary Tree - LeetCode

时间:2019-03-15 00:47:58      阅读:172      评论:0      收藏:0      [点我收藏+]

题目链接

Maximum Depth of Binary Tree - LeetCode

注意点

  • 不要访问空结点

解法

解法一:递归,当前深度与最大深度相比,是否大于,大于就更新。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int dfs(int dep,int& max,TreeNode* node)
    {
        if(dep > max) max = dep;
        if(node->left) max = dfs(dep+1,max,node->left);
        if(node->right) max = dfs(dep+1,max,node->right);
        return max;
    }
    int maxDepth(TreeNode* root) {
        if(!root) return 0;
        int dep = 1;
        int max = 1;
        return dfs(dep,max,root);
    }
};

技术分享图片

小结

  • 在写if(!root)这种语句的时候一定要清楚的认识到root是NULL才会为真。

Maximum Depth of Binary Tree - LeetCode

原文:https://www.cnblogs.com/multhree/p/10534474.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!