leetcode 二叉树系列
1.二叉树转链表
Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
class Solution {
public:
vector<TreeNode *>v;
void flatten(TreeNode *root)
{
v.clear();
if(root==NULL)return;
PreOrder(root);
TreeNode *p=root;
for(int i=1;i<v.size();i++)
{
TreeNode *q=v[i];
p->left=NULL;
p->right=q;
p=q;
}
}
void PreOrder(TreeNode *root)
{
if(root)v.push_back(root);
if(root->left)PreOrder(root->left);
if(root->right)PreOrder(root->right);
}
};
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) {
return _sortArrayToBST(num, 0, num.size()-1);
}
private:
TreeNode *_sortArrayToBST(vector<int> &num, int i, int j){
if(i>j){
return NULL;
}
else{
int r = (i+j+1)/2;
TreeNode *root = new TreeNode(num[r]);
root->left = _sortArrayToBST(num, i, r-1);
root->right = _sortArrayToBST(num, r+1, j);
return root;
}
}
};
浙公网安备 33010602011771号