leetcode 104 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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

题目的意思是求二叉树的深度,难度的easy。博主在刷的过程中虽然是一遍就AC了,但是代码比较丑陋,如下:

/**
 * 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) {
        int ret = 0;
        if(!root)
            return ret;
        dfsDepth(ret, 1, root);
        return ret;
    }
    
    void dfsDepth(int &ret, int curr_depth, TreeNode *root)
    {
        if(!root)
            return;
        if(ret < curr_depth)
            ret = curr_depth;
        dfsDepth(ret, curr_depth + 1, root->left);
        dfsDepth(ret, curr_depth + 1, root->right);
    }
};

思路就是通过常规的dfs遍历每个节点,如果ret小于当前节点的深度,则ret变为当前的深度。提交后看了别人的解法,深觉代码简洁优雅,结题思路一致,搬运如下:

    int maxDepth(TreeNode *root) {
        if (root == null) {
            return 0;
        }

        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }

猜你喜欢

转载自blog.csdn.net/happyjume/article/details/85217757