Binary Tree Level Order Traversal II
Description
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).
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] ]
Link
Method
- Level order traversal then reverse result vector
- x
Example
- 1
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { /** * @param root : The root of binary tree. * @return : buttom-up level order a list of lists of integer */ public: vector<vector<int>> levelOrderBottom(TreeNode *root) { // write your code here vector<vector<int>> result; if (!root) { return result; } int depth = 0; int count = 1; queue<TreeNode*> q; // bfs q.push(root); while (!q.empty()) { // front proc TreeNode* cur = q.front(); q.pop(); --count; // record if (result.size() < depth + 1) { result.push_back(vector<int>(1, cur->val)); } else { result[depth].push_back(cur->val); } // push next level if (cur->left) { q.push(cur->left); } if (cur->right) { q.push(cur->right); } // update depth/count if (count == 0) { count = q.size(); ++depth; } } // reversed level reverse(result.begin(), result.end()); return result; } };
Similar problems
x
Tags
x