【LeetCode笔记】Maximum Depth of Binary Tree 二叉树最大深度 递归&非递归

轻而易举的敲下了经典的递归程序:

/**
 * 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;
        else
            return maxDepth(root->left)>maxDepth(root->right)? maxDepth(root->left)+1:maxDepth(root->right)+1;
    }
};
然后系统告诉我,38个测试用例过了36个,然后

 Time Limit Exceeded

好吧,递归确实好用,但是占用的资源有点多,对于树很大的情况不好使。


非递归方法:

又让我想到了第二题!求树的最大深度呀->第二题用二维vector按层存储二叉树的时候,第二维的个数不就是层数嘛,层数不就是深度嘛!

同样的,使用queue先进先出,当上一层全部pop出去的时候,当前层刚好全部在里面。所以每得到一层,count++

/**
 * 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) {
        queue<TreeNode*> q;
        TreeNode* p;
        int count = 0;
        if (root == NULL)
            return 0;
        else{
            q.push(root);
            while (!q.empty()){
                int size = q.size();
                for (int i=0;i<size;i++){
                    p = q.front();  //注意取节点的代码要在第二层循环里面,因为每一个for循环全部执行完,
                    q.pop();        //就相当于拿走了上一层的全部节点,并存入了下一层的全部节点
                    if(p->left!=NULL)
                        q.push(p->left);
                    if (p->right!=NULL)
                        q.push(p->right);
                }
                count++;
            }
        }
        return count;
    }
};



猜你喜欢

转载自blog.csdn.net/macidoo/article/details/69830211