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

leetcode || 104、Maximum Depth of Binary Tree

时间:2015-04-21 11:20:10      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:leetcode   二叉树   dfs   二叉树深度   

problem:

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.

Hide Tags
 Tree Depth-first Search
题意:输出二叉树的深度

thinking:

深度优先搜索,记录最大深度

code:

/**
 * Definition for binary tree
 * 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==NULL)
            return 0;
        int max_dep=0;
        dfs(0,max_dep,root);
        return max_dep;
    }
protected:
    void dfs(int dep,int &max_dep,TreeNode *node)
    {
        if(node==NULL)
            return;
        dep++;
        max_dep = max(max_dep,dep);
        if(node->left!=NULL)
            dfs(dep,max_dep,node->left);
        if(node->right!=NULL)
            dfs(dep,max_dep,node->right);
    }
};


leetcode || 104、Maximum Depth of Binary Tree

标签:leetcode   二叉树   dfs   二叉树深度   

原文地址:http://blog.csdn.net/hustyangju/article/details/45166393

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