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] ]
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> levelOrderBottom(TreeNode* root) { queue<TreeNode*> nodes; vector< vector<int> > result; vector<int> tmp; if(NULL==root) return result; nodes.push(root); while(!nodes.empty()) { int length=nodes.size(); int i=0; while(i<length) {//弹出本层所有结点后,跳出循环,length的值在循环时是不会改变的 TreeNode* tmpNode=nodes.front(); tmp.push_back(tmpNode->val); if(tmpNode->left) nodes.push(tmpNode->left); if(tmpNode->right) nodes.push(tmpNode->right); nodes.pop(); i++; } result.push_back(tmp); tmp.clear(); } reverse(result.begin(),result.end()); return result; } };
又是层序遍历的方式,层序遍历反复出现过多次:求二叉树的最小深度、右侧能看到的结点、统计特殊形式的二叉树结点个数...