[Leetcode] Binary tree level order traversal ii二叉树层次遍历

时间:2021-07-12 05:06:58

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
\
5

The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".

 
这一题和Binary tree level order traversal的区别在于,输出结果是从下往上一层层的遍历节点,有两种小聪明的方法:一、在上一题的最后反转res然后输出;二、使用栈。得到每一层的节点后,不直接压入res中,先存入栈中,然后利用栈先进后出的特点,再压入res,实现反转。这两题关键的部分在于如何单独得到每一层的节点。以下两种方法的主体部分也可以用上一题中的方法一,其核心思想不变
方法一:最后反转
 /**
* 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); while( !Q.empty())
{
int count=;
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++;
}
res.push_back(levNode);
}
reverse(res.begin(),res.end()); //在上一题的基础上增加一行
return res;
}
};

方法二:利用栈

/**
* 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=;
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;
}
};