【LeetCode】Binary Tree Level Order Traversal II

제목:


Binary Tree Level Order Traversal II


Total Accepted: 18664
Total Submissions: 59503
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]
]

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
분석:
사실은 두 갈래 나무의 차원이 두루 흐르고 출력할 때 밑에서 위로 올라가는데 이것은 창고 하나만 사용하면 된다.
코드:
class Solution {
public:
    vector<vector<int> > levelOrderBottom(TreeNode *root) {
        vector<vector<int> > ret;
        
        if (!root) {
            return ret;
        }
        
        int cnt = 0;
        int num = 1;
        
        stack<vector<int> >  stk;
        queue<TreeNode*>     q;
        
        q.push(root);
        stk.push(vector<int>());
        while (!q.empty()) {
            TreeNode *cur = q.front();
            q.pop();
            
            stk.top().push_back(cur->val);
            
            if (cur->left) 
                q.push(cur->left);
            if (cur->right)
                q.push(cur->right);
            
            if (++cnt == num && !q.empty()) {
                stk.push(vector<int>());
                num = q.size();
                cnt = 0;
            }
        }
        
        while (!stk.empty()) {
            ret.push_back(stk.top());
            stk.pop();
        }
        return ret;
    }

};

좋은 웹페이지 즐겨찾기