LeetCode:Binary Tree Level Order Traversal II

Binary Tree Level Order Traversal II

Total Accepted: 60177 Total Submissions: 188407 Difficulty: Easy

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]
























code:

/**
 * 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:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> ret;
        if(NULL == root) return ret;
        queue<TreeNode *> q[2];  // 队列实现层次遍历,需要两个
        stack<vector<int>> s;  // 保存中间结果
        int cur=0;
        q[cur].push(root);
        while(!q[cur].empty()) {
            vector<int> tmp;
            while(!q[cur].empty()) {
                TreeNode *p = q[cur].front();
                tmp.push_back(p->val);
                if(p->left) q[cur^1].push(p->left);  // 交替入队
                if(p->right) q[cur^1].push(p->right);  
                q[cur].pop();
            }
            cur^=1;
            s.push(tmp);
        }
        while(!s.empty()) {
            ret.push_back(s.top());
            s.pop();
        }
        return ret;
    }
};


阅读更多
版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/itismelzp/article/details/49906839
个人分类: LeetCode OJ
所属专栏: LeetCode解题记录
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

LeetCode:Binary Tree Level Order Traversal II

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭