leetcode 104. 二叉树的最大深度

深度优先搜索代码:

/**
 * 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 depth=0,high=0;
        dfs(root,depth,high);
        return depth;
    }
    void dfs(TreeNode* root,int &depth,int high){
        if(root==NULL) return;
        high++;
        if(high>depth) depth=high;
        dfs(root->left,depth,high);
        dfs(root->right,depth,high);
        high--;
    }
};

精简版:

/**
 * 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) {
        return root==NULL? 0: 1+max(maxDepth(root->left),maxDepth(root->right));
    }
};

 

posted @ 2019-04-11 20:48  Joel_Wang  阅读(113)  评论(0编辑  收藏  举报