104-求二叉树最大深度

1、递归

思路就是:递归进行左子树和右子树,最终比较最长的长度,进而是该二叉树的深度

 1 class Solution {
 2 public:
 3     int maxDepth(TreeNode* root) 
 4     {
 5         if(root==NULL)
 6         {
 7             return 0;      //访问到空节点,深度为0
 8         }
 9         int left_length=maxDepth(root->left);   //左展开去求深度
10         int right_length=maxDepth(root->right);
11         if(left_length>right_length)
12         {
13             return left_length+1;                 //最开始的树根结点没有算进去,故加一
14         }
15         else
16         {
17             return right_length+1;
18         }
19     }
20 }

2、迭代法

思路:声明一个栈,从根结点到左子树开始放入栈,如果放到空结点向上一级返回去访问右子树,返回右子树的同时记录已经访问的深度。详细见代码

 1 class Solution {
 2 public:
 3     int maxDepth(TreeNode* root) {
 4         if(root==NULL) return 0;
 5         stack<pair<TreeNode*,int>> s;
 6         TreeNode *p=root;
 7         int Maxdeep=0;
 8         int deep=0;
 9         while(!s.empty()||p!=NULL)
10         {
11             while(p!=NULL)
12             {
13                 s.push(pair<Treenode*,int> (p,++deep));
14                 p=p->left;
15             }
16             p=s.top().first;        //一直访问左子树访问到空节点,返回上一级遇到的结点
17             deep=s.top().second;
18             if(deep>Maxdeep)
19             {
20                 Maxdeep=deep;
21             }
22             s.pop();//将这个点弹出,开始访问上一个点的右子树了
23             p=p->right;
24         }
25         return Maxdeep;
26 }

总结:多学习递归和迭代的方法,体会其中的思路

其中递归要注意递归的停止条件和递归内容

迭代比较符合正常的思维,但是要注意具体stack<pair<int,int>>的用法

猜你喜欢

转载自www.cnblogs.com/nxnslc-blog/p/12374797.html
今日推荐