题目描述:

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.

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

题意是要我们返回二叉树最深的分支是多少层。

解题思路:

我的思路是用递归遍历每一个节点,每一次节点往下分支都比较两个分支最深的层数,返回最大的层数。

我的代码:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int maxD(TreeNode* cur,int depth){
13         if(!cur)
14             return depth;
15         else{
16             int left=maxD(cur->left,depth+1);
17             int right=maxD(cur->right,depth+1);
18             return (left>right)?left:right;
19         }
20     }
21     int maxDepth(TreeNode* root) {
22         return maxD(root,0);
23     }
24 };

 

他人代码:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int maxDepth(TreeNode* root) {
13     //相比我的代码,这段代码没有再弄一个函数,也不用每次都传一个层数的形参下去,简便了许多。不过思路还是一样的。
14         if(!root)
15             return 0;
16         else
17             return max(maxDepth(root->left),maxDepth(root->right))+1;
18     }
19 };

 

posted on 2018-02-08 17:40  宵夜在哪  阅读(89)  评论(0编辑  收藏  举报