题目:
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii
思路:
1、模板题,层次遍历后前后翻转一下即可
Python代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.ret = []
def bfs(self, root):
if not root:
return []
deque = [root]
while deque:
temp = []
nex = []
for item in deque:
temp.append(item.val)
if item.left:
nex.append(item.left)
if item.right:
nex.append(item.right)
deque = nex
self.ret.append(temp)
return self.ret[::-1]
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
return self.bfs(root)
C++代码:
/**
* 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>> ret;
vector<vector<int>> bfs(TreeNode* root){
if(root == nullptr){
return ret;
}
vector<TreeNode* > deque;
deque.push_back(root);
while(deque.size()>0){
vector<TreeNode* > nex;
vector<int> temp;
for (auto item : deque){
temp.push_back(item->val);
if (item->left){
nex.push_back(item->left);
}
if (item->right){
nex.push_back(item->right);
}
}
deque.swap(nex);
ret.push_back(temp);
}
reverse(ret.begin(), ret.end());
return ret;
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
return bfs(root);
}
};
网友评论