# leetcode -day22 Binary Tree Level Order Traversal II & Convert Sorted Array to Binary Search Tree

66 篇文章 0 订阅
1、
﻿﻿

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],
]

class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) {
vector<vector<int>> result;
if(root == NULL){
return result;
}
vector<int> levelVec;
queue<TreeNode*> levelStack;
queue<TreeNode*> newStack;
levelStack.push(root);
levelVec.push_back(root->val);
result.push_back(levelVec);
while(!levelStack.empty()){
levelVec.clear();
while(!levelStack.empty()){
TreeNode* node = levelStack.front();
levelStack.pop();
if(node->left){
newStack.push(node->left);
levelVec.push_back(node->left->val);
}
if(node->right){
newStack.push(node->right);
levelVec.push_back(node->right->val);
}
}
if(levelVec.empty()){
break;
}
result.push_back(levelVec);
levelStack.swap(newStack);
}
int start = 0;
int end = result.size()-1;
while(start < end){
result[start].swap(result[end]);
++start;
--end;
}
return result;
}
};

2、Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &num){
if(num.empty()){
return NULL;
}
return convertCore(num,0,num.size()-1);
}
TreeNode* convertCore(vector<int>& num, int start, int end){
if(start > end || start < 0 || end >= num.size()){
return NULL;
}
TreeNode* root = NULL;
if(start == end){
root = new TreeNode(num[start]);
}else if(start < end ){
int middle = (start+end)/2;
root = new TreeNode(num[middle]);
TreeNode* leftNode = convertCore(num,start,middle-1);
TreeNode* rightNode = convertCore(num,middle+1,end);
root->left = leftNode;
root->right = rightNode;
}
return root;
}
};

08-25 473

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

xiao囡囡

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。