[Leetcode] 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,#,#,15,7},
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7] [9,20], [3], ]
confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".
这一题和Binary tree level order traversal的区别在于,输出结果是从下往上一层层的遍历节点,有两种小聪明的方法:一、在上一题的最后反转res然后输出;二、使用栈。得到每一层的节点后,不直接压入res中,先存入栈中,然后利用栈先进后出的特点,再压入res,实现反转。这两题关键的部分在于如何单独得到每一层的节点。以下两种方法的主体部分也可以用上一题中的方法一,其核心思想不变
方法一:最后反转
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 { 12 public: 13 vector<vector<int>> levelOrderBottom(TreeNode* root) 14 { 15 vector<vector<int>> res; 16 queue<TreeNode *> Q; 17 if(root) Q.push(root); 18 19 while( !Q.empty()) 20 { 21 int count=0; 22 int levCount=Q.size(); 23 vector<int> levNode; 24 25 while(count<levCount) 26 { 27 TreeNode *curNode=Q.front(); 28 Q.pop(); 29 levNode.push_back(curNode->val); 30 if(curNode->left) 31 Q.push(curNode->left); 32 if(curNode->right) 33 Q.push(curNode->right); 34 count++; 35 } 36 res.push_back(levNode); 37 } 38 reverse(res.begin(),res.end()); //在上一题的基础上增加一行 39 return res; 40 } 41 };
方法二:利用栈
/** * 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>> res; queue<TreeNode *> Q; if(root) Q.push(root); stack<vector<int>> stk; while( !Q.empty()) { int count=0; int levCount=Q.size(); vector<int> levNode; while(count<levCount) { TreeNode *curNode=Q.front(); Q.pop(); levNode.push_back(curNode->val); if(curNode->left) Q.push(curNode->left); if(curNode->right) Q.push(curNode->right); count++; } stk.push(levNode); //压入栈 } while(!stk.empty()) //出栈 { res.push_back(stk.top()); stk.pop(); } return res; } };