标签:
iven 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] ]
思路:思路和Binary Tree Level Order Traversal相同,在最后的时候reverse.
1 /** 2 * Definition for binary tree 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<vector<int> > result; 14 if (root == nullptr) return result; 15 16 queue<TreeNode *> current, next; 17 vector<int> level; 18 19 current.push(root); 20 while (!current.empty()) { 21 while (!current.empty()) { 22 TreeNode *p = current.front(); 23 current.pop(); 24 level.push_back(p->val); 25 if (p->left != nullptr) next.push(p->left); 26 if (p->right != nullptr) next.push(p->right); 27 } 28 result.push_back(level); 29 level.clear(); 30 swap(current, next); 31 } 32 33 reverse(result.begin(), result.end()); 34 return result; 35 } 36 };
[LeetCode] Binary Tree Level Order Traversal II
标签:
原文地址:http://www.cnblogs.com/vincently/p/4229779.html