首页 > 代码库 > Leetcode 107. Binary Tree Level Order Traversal II

Leetcode 107. Binary Tree Level Order Traversal II

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]]

 1 /** 2  * Definition for a binary tree node. 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     vector<vector<int>> levelOrderBottom(TreeNode* root) {13         vector<int> row;14         vector<vector<int>> v;15         if(root == NULL)16             return v;17         queue<TreeNode*> qu;18         TreeNode* node;19         qu.push(root);20         while(!qu.empty()){21             int l = qu.size();22             for(int i = 0; i < l; i++){23                  node = qu.front();24                  qu.pop();25                  row.push_back(node -> val);26                  if(node -> left != NULL)27                     qu.push(node -> left);28                 if(node -> right != NULL)29                     qu.push(node -> right);30             }31             v.insert(v.begin(), row);32             row.clear();33         }34         return v;35     }36 };

 

 

Leetcode 107. Binary Tree Level Order Traversal II