LeetCode Maximum Depth of Binary Tree
來源:程序員人生 發(fā)布時(shí)間:2015-04-11 09:44:36 閱讀次數(shù):2573次
1.題目描寫
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.
2.解決方案1
class Solution {
public:
int maxDepth(TreeNode *root) {
if(root == NULL){
return 0;
}
deque<TreeNode*> deqNodes;
deqNodes.push_back(root);
int depth = 0;
int alreadyDoneCount = 1;
while(deqNodes.empty() == false){
TreeNode* lastNode = deqNodes.back();
deqNodes.pop_back();
alreadyDoneCount--;
if(lastNode->left){
deqNodes.push_front(lastNode->left);
}
if(lastNode->right){
deqNodes.push_front(lastNode->right);
}
if(alreadyDoneCount == 0){
++depth;
alreadyDoneCount = deqNodes.size();
}
}
return depth;
}
};
思路:采取寬度優(yōu)先搜索,
只有當(dāng)添加的全處理了,樹的深度才增加1,這個(gè)是個(gè)小技能。
3.解決方案2
class Solution {
public:
int maxDepth(TreeNode *root) {
if(root == NULL ){
return 0;
}else if(root != NULL && (root->left == NULL && root->right == NULL)){
return 1;
}
int leftTreeDepth = maxDepth(root->left);
int rightTreeDepth = maxDepth(root->right);
int maxDepth = leftTreeDepth > rightTreeDepth ? leftTreeDepth : rightTreeDepth;
return maxDepth + 1;
}
};
思路:樹的遍歷固然可以用遞歸,但會比較慢。
http://www.waitingfy.com/archives/1586
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈