leetcode_104题——Maximum Depth of Binary Tree (二叉树,递归,队列,还有递归没想出来)
2015-04-14 15:34
459 查看
Maximum Depth of Binary Tree
Total Accepted: 59837 Total Submissions: 132940My SubmissionsQuestion 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) { }
相关文章推荐
- 【LeetCode 104_二叉树_遍历】Maximum Depth of Binary Tree
- 【LeetCode-面试算法经典-Java实现】【104-Maximum Depth of Binary Tree(二叉树的最大深度)】
- Leetcode 104 Maximum Depth of Binary Tree 二叉树的最大深度
- 【LeetCode-面试算法经典-Java实现】【104-Maximum Depth of Binary Tree(二叉树的最大深度)】
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | 深度优先与广度优先深入理解
- LeetCode 104 Maximum Depth of Binary Tree(二叉树的最大深度)
- 【LeetCode笔记】Maximum Depth of Binary Tree 二叉树最大深度 递归&非递归
- Leetcode 104 Maximum Depth of Binary Tree 二叉树
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | Easy
- [LeetCode-104] Maximum Depth of Binary Tree(二叉树最大深度)
- LeetCode:104_Maximum Depth of Binary Tree | 二叉树的最大深度 | Easy
- LeetCode----Maximum Depth of Binary Tree 求二叉树最大深度
- [Leetcode 8] 104 Maximum Depth of Binary Tree
- 【LeetCode】(104)Maximum Depth of Binary Tree(Easy)
- LeetCode 104 Maximum Depth of Binary Tree
- Leetcode No.104 Maximum Depth of Binary Tree 遍历二叉树的深度
- <LeetCode OJ> (104 / 111) Maximum & Minimum Depth of Binary Tree
- leetcode-104-Maximum Depth of Binary Tree
- leetcode104 Maximum Depth of Binary Tree
- Leetcode 104 Maximum Depth of Binary Tree