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).
給一個二元樹,從底部往上地按照階層遍歷回傳它每個節點的值。(從左到右,一層一層從樹葉到樹根)
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
level order
之後,再把結果反向。
/**
* 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:
void BFS(vector<vector<int>>& ans,vector<int>& nodes,vector<pair<TreeNode*,int>>& queue,int &level)
{
//take new node from queue
pair<TreeNode*,int> n = queue.front();
queue.erase(queue.begin());
if(!n.first)return;
//check level
if(level==n.second)
nodes.push_back(n.first->val);
else
{
level = n.second;
ans.push_back(nodes);
nodes.clear();
nodes.push_back(n.first->val);
}
//push next node into queue
queue.push_back(pair<TreeNode*,int>(n.first->left,n.second+1));
queue.push_back(pair<TreeNode*,int>(n.first->right,n.second+1));
//run until queue is empty
while(queue.size()!=0)
BFS(ans,nodes,queue,level);
//check last level is pushed
if(nodes.size()!=0)
{
ans.push_back(nodes);
nodes.clear();
}
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> ans;
vector<int> nodes;
int level=0;
vector<pair<TreeNode*,int>> queue(1,pair<TreeNode*,int>(root,0));
BFS(ans,nodes,queue,level);
reverse(ans.begin(),ans.end());
return ans;
}
};
LeetCode
C++
1. Two Sum
Nov 15, 2023You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:
Nov 15, 2023Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.
Nov 9, 2023There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.
Nov 9, 2023or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up