1. 程式人生 > >leetcode 104 Maximum Depth of Binary Tree

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;
    }