LeetCode探索之旅(23)-104二叉树的深度

继续刷LeetCode,第104题,求二叉树的深度。

分析:
使用递归的方法,遍历左右两个孩子节点,判断哪个较大,就返回其加一。

问题:
1、求二叉树的深度的方法。

附上代码:

/**
 * 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 maxDepth(TreeNode* root) {
        if(root==nullptr)
            return 0;
        int lh=maxDepth(root->left);
        int rh=maxDepth(root->right);
        return lh>rh?lh+1:rh+1;
    }
};

猜你喜欢

转载自blog.csdn.net/JerryZengZ/article/details/87977183