#104 Maximum Depth of Binary Tree

原创 2015年07月09日 20:50:59

再来选一道通过率最高的题目~

#104 Maximum Depth of Binary Tree

这是一道二叉树的题目,非常简单,只要DFS就可以啦。不过再次感慨一下要多多提高记事本编程能力呀。

题目要求就是找出从根节点到叶子节点最长路径的depth。不过有一个隐藏的trap,root可能为空哦,第一次就没有考虑到结果还要再提交一次=。=

/**
 * 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 {
private:
    int max = 1;
    void godown(TreeNode* node, int depth) {
        if(node->left!=NULL) {
            godown(node->left, depth+1);
        }
        if(node->right!=NULL) {
            godown(node->right, depth+1);
        }
        if(node->left==NULL && node->right==NULL) {
            if(depth > max) {
                max = depth;
            }
        }
    }
public:
    int maxDepth(TreeNode* root) {
        if (root==NULL) {
            return 0;
        }
        godown(root,1);
        return max;
    }
};

当然BFS也是可以的啦,效率也一样,不过还要用容器好麻烦,还是DFS简单嘿嘿。

至于说用返回值加一加的方法写DFS我当然也会啊,不过还是习惯带着变量往下走好开心好开心,只是多定义了一个max而已没有实质差别咯,不要在意这些细节……

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

No104. Maximum Depth of Binary Tree

一、题目描述 Given a binary tree, find its maximum depth.The maximum depth is the number of nodes along t...

Leetcode-104. Maximum Depth of Binary Tree c语言

来源:104. Maximum Depth of Binary Tree 题目要求: Given a binary tree, find its maximum depth. The max...
  • tzh476
  • tzh476
  • 2016年07月03日 19:06
  • 519

LeetCode104 Maximum Depth of Binary Tree

详细见:leetcode.com/problems/maximum-depth-of-binary-tree Java Solution: github package leetcod...
  • zxwtry
  • zxwtry
  • 2017年04月27日 22:00
  • 215

104/111 Maximum/Minimum Depth of Binary Tree(二叉树求深度)

104 Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the...

leetCode 104. Maximum Depth of Binary Tree

题目链接:https://leetcode.com/problems/maximum-depth-of-binary-tree/     题目内容: Given a binary tree, ...

LeetCode笔记:104.Maximum Depth of Binary Tree

计算二叉树的最大深度

[LeetCode]104.Maximum Depth of Binary Tree

【题目】 Maximum Depth of Binary Tree  Total Accepted: 5260 Total Submissions: 11532My Submissions ...

LeetCode#104. Maximum Depth of Binary Tree

104. Maximum Depth of Binary Tree Given a binary tree, find its maximum depth. The maximum dep...

【LeetCode】104. Maximum Depth of Binary Tree(DFS|BFS)

原题Given a binary tree, find its maximum depth.The maximum depth is the number of nodes along the lon...

Leetcode 104. Maximum Depth of Binary Tree (Easy) (cpp)

Leetcode 104. Maximum Depth of Binary Tree (Easy) (cpp)
  • Niko_Ke
  • Niko_Ke
  • 2016年07月22日 16:50
  • 274
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:#104 Maximum Depth of Binary Tree
举报原因:
原因补充:

(最多只允许输入30个字)