是这题的变种
对一棵树从最后一次开始层次遍历,并返回结果。例如:
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] ]
思路:用一个queue遍历每行,行与行之间NULL分开,然后用stack记录每次的结果,最后将stack中的导出:
/** * Definition for binary tree * 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) { vector<vector<int> > ans; if (!root) return ans; queue<TreeNode *> que; stack<vector<int> > sta; vector<int> tmp; TreeNode *p; que.push(root); que.push(NULL); while(!que.empty()) //先把结果放在stack中 { p = que.front(); if (p != NULL) { tmp.push_back(p -> val); if (p -> left) que.push(p -> left); if (p -> right) que.push(p -> right); que.pop(); } else { que.pop(); sta.push(tmp); tmp.clear(); if (!que.empty()) { que.push(NULL); } } } while(!sta.empty()) // 导出结果 { ans.push_back(sta.top()); sta.pop(); } return ans; } };
后面发现其实stack是多此一举了,可以直接输入到ans中,然后最后利用reverse函数将容器反转即可。
/** * Definition for binary tree * 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) { vector<vector<int> > ans; if (!root) return ans; queue<TreeNode *> que; vector<int> tmp; TreeNode *p; que.push(root); que.push(NULL); while(!que.empty()) //先把结果放在stack中 { p = que.front(); if (p != NULL) { tmp.push_back(p -> val); if (p -> left) que.push(p -> left); if (p -> right) que.push(p -> right); que.pop(); } else { que.pop(); ans.push_back(tmp); tmp.clear(); if (!que.empty()) { que.push(NULL); } } } reverse(ans.begin(), ans.end()); return ans; } };