码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 104. 二叉树的最大深度

时间:2019-04-11 20:57:25      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:深度优先   技术   bin   http   img   mic   roo   root   treenode   

技术图片

深度优先搜索代码:

/**
 * 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));
    }
};

 

leetcode 104. 二叉树的最大深度

标签:深度优先   技术   bin   http   img   mic   roo   root   treenode   

原文地址:https://www.cnblogs.com/joelwang/p/10692423.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!