Maximum Depth of Binary Tree

题目链接

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才会为真。
原文地址:https://www.cnblogs.com/multhree/p/10534474.html