这道题是LeetCode里的第104道题。
给出题目:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树[3,9,20,null,null,15,7]
,3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。
DFS 递归算法,简单的二叉树题。如果看不懂代码,建议学习一下二叉树,这可是基础啊!
给出代码:
递归法:
/**
* 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 leftDepth=0;
if(root->left!=NULL)
leftDepth=maxDepth(root->left);
int rightDepth=0;
if(root->right!=NULL)
rightDepth=maxDepth(root->right);
return max(leftDepth,rightDepth)+1;
}
};
//精简版:
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root)return 0;
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
};
迭代法:
/**
* 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)return 0;
queue<TreeNode*> qt;
int max=0;
int preNodeCount=1;
int nodeCount=0;
qt.push(root);
while(qt.size()!=0){
TreeNode* tn=qt.front();
preNodeCount--;
qt.pop();
if(tn->left!=NULL){
qt.push(tn->left);nodeCount++;
}
if(tn->right!=NULL){
qt.push(tn->right);nodeCount++;
}
if(preNodeCount==0){
preNodeCount=nodeCount;
nodeCount=0;
max++;
}
}
return max;
}
};
给出结果:
两个结果都一样,之前做的时候还是 4ms 呢!可能是实例变多了。
给出总结:
能用递归法的就可以试一下用迭代法解决,果不其然,有所收获!一开始使用迭代法使用的是栈,使用栈无论怎么操作,都会产生无限循环的问题,无法得到最终解,因为一般来讲,堆栈适合用来求深度,这道题也是要求深度,可是万万没想到,这道题使用队列来实现迭代,我认为队列适合来求广度,但这题超出我的预料。到时候在找找看有没有用堆栈求解的代码。
哦,想起来了,或许可以用前中后序的代码做文章,改造一下用来求最大深度!!!