104. Maximum Depth of Binary Tree

来源:互联网 发布:淘宝嘉贝逸飞旗舰店 编辑:程序博客网 时间:2024/06/05 19:58

1.Question

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.

2.Code

/** * 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) {        if(root == NULL) return 0; int left_depth = maxDepth(root->left), right_depth = maxDepth(root->right);if(left_depth >= right_depth)return left_depth + 1;elsereturn right_depth + 1;           }};

3.Note

a. 对于树,就要想到递归。本题思想是,返回左右子树中最大深度,通过递归来实现。


b.最初版本

class Solution {public:    int maxDepth(TreeNode* root) {        if(root == NULL) return 0;if(maxDepth(root->left) >= maxDepth(root->right))return maxDepth(root->left) + 1;elsereturn maxDepth(root->right) + 1;    }};


以上这个版本是第一次写的版本,出现了 Time limited exceed。 然后参考了别人的时候发现,我的算法的缺点在于:在比较时算了两遍maxDepth(),比较完大小之后,return 语句中又算了一遍maxDepth()。这没必要。所以可以考虑另外定义一个变量名来保存maxDepth() 的结果。


c.更简洁版本

class Solution {public:    int maxDepth(TreeNode* root) {        if(root == NULL) return 0;else return max(maxDepth(root->left),maxDepth(root->right)) + 1;    }};

这个是最后想到的,更简洁的版本,通过调用max()函数来简化代码。两行即可搞定。


0 0
原创粉丝点击