码迷,mamicode.com
首页 > 其他好文 > 详细

Maximum Depth of Binary Tree - LeetCode

时间:2019-03-15 01:16:40      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:src   语句   leetcode   int   root   public   for   code   ble   

题目链接

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

标签:src   语句   leetcode   int   root   public   for   code   ble   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!