首页 > 其他 > 详细

LeetCode Maximum Depth of Binary Tree

时间:2015-03-06 11:19:46      阅读:191      评论:0      收藏:0      [点我收藏+]

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;
    }
};

思路:采用宽度优先搜索
只有当添加的全处理了,树的深度才增加1,这个是个小技巧。


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

LeetCode Maximum Depth of Binary Tree

原文:http://blog.csdn.net/fox64194167/article/details/44096519

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!