您的位置:首页 > 其它

leetcode_104题——Maximum Depth of Binary Tree (二叉树,递归,队列,还有递归没想出来)

2015-04-14 15:34 459 查看

Maximum Depth of Binary Tree

Total Accepted: 59837 Total Submissions: 132940My Submissions
Question Solution

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

Have you met this question in a real interview?
Yes

No

Discuss

1.采用递归的方法来做

#include<iostream>
#include<vector>
using namespace std;

struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

//用递归的方法来做(有点类似于动态规划的感觉)
int max(int a,int b);
int maxDepth(TreeNode *root)
{
int left,right;
if(root==NULL)
return 0;
left=maxDepth(root->left);//左子树的深度
right=maxDepth(root->right);//右子树的深度
return 1+max(left,right);//选取其中深度大的那个,再加上本身的一,为本身这个结点深度
}
int max(int a,int b)
{
if(a>=b)
return a;
else
return b;
}
int main(int argc,char** argv)
{

}


  2.采用队列的方式来做

#include<iostream>
#include<vector>
#include<queue>
using namespace std;

struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

//采用队列的方式来做,采用队列的方式一层一层的对二叉树进行遍历,并记录层数
int maxDepth(TreeNode *root)
{
if(root==NULL)
return 0;
int deep=0;//深度
int row_size=1;//每一层的元素个数(第一层只有一个根节点)
queue<TreeNode*> temp;//算法所用的队列.

temp.push(root);
while(!temp.empty())//直到队列为空才停止
{
TreeNode* temp_node;
while(row_size--)//依次的遍历每一层,将下一层的每一个元素都进队列,并将上一层
{//的队列都出列。
temp_node=temp.front();
if(temp_node->left!=NULL)
temp.push(temp_node->left);
if(temp_node->right!=NULL)
temp.push(temp_node->right);
temp.pop();
}
row_size=temp.size();//记录下这一层的元素有多少个
deep+=1;//记录深度
}
return deep;
}

int main(int argc,char** argv)
{

}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: