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,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

 

return its bottom-up level order traversal as:

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

 

class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> res;
        if(root == nullptr) return res;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()) {
            vector<int> single_res;
            int cnt = q.size();
            for(int i = 0; i < cnt;++i) {
                root = q.front();
                q.pop();
                single_res.push_back(root->val);
                if(root->left != nullptr) q.push(root->left);
                if(root->right !=nullptr) q.push(root->right);
            }
            res.insert(res.begin(),single_res);
        }
        return res;
    }
};

 

 

 1 public class Solution {
 2     public List<List<Integer>> levelOrderBottom(TreeNode root) {
 3         Queue<TreeNode> queue = new LinkedList<TreeNode>();
 4         List<List<Integer>> wrapList = new LinkedList<List<Integer>>();
 5         
 6         if(root == null) return wrapList;
 7         
 8         queue.offer(root);
 9         while(!queue.isEmpty()){
10             int levelNum = queue.size();
11             List<Integer> subList = new LinkedList<Integer>();
12             for(int i=0; i<levelNum; i++) {
13                 if(queue.peek().left != null) queue.offer(queue.peek().left);
14                 if(queue.peek().right != null) queue.offer(queue.peek().right);
15                 subList.add(queue.poll().val);
16             }
17             wrapList.add(0, subList);
18         }
19         return wrapList;
20     }
21 }

 

相关文章:

  • 2021-05-28
  • 2021-10-18
  • 2022-02-09
  • 2021-05-24
  • 2022-01-07
  • 2022-01-11
猜你喜欢
  • 2021-09-21
  • 2021-12-10
  • 2021-09-17
  • 2022-12-23
  • 2021-06-30
相关资源
相似解决方案