二叉树的最近公共祖先
class Solution {
public:
map<TreeNode*, TreeNode*> parent;
int depth(TreeNode* root, TreeNode* node){
if(root == NULL)
return 999999;
if(root == node)
return 0;
parent[root->left] = root;
parent[root->right] = root;
return min(depth(root->left, node), depth(root->right, node)) + 1;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
int pd = depth(root, p);
int qd = depth(root, q);
if(pd > qd){
swap(p, q);
swap(pd, qd);
}
while(pd < qd){
q = parent[q];
qd -= 1;
}
while(p != q){
p = parent[p];
q = parent[q];
}
return p;
}
};
从有序数组中构造二叉查找树
class Solution {
public:
TreeNode* build(vector<int>& nums, int start, int end){
if(start > end)
return NULL;
int mid = (start + end) / 2;
TreeNode* root = new TreeNode(nums[mid]);
if(start == end)
return root;
root->left = build(nums, start, mid-1);
root->right = build(nums, mid+1, end);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return build(nums, 0, nums.size()-1);
}
};
根据有序链表构造平衡的二叉查找树
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(head == NULL)
return NULL;
if(head->next == NULL)
return new TreeNode(head->val);
ListNode* fast, *slow, *slow_par;
fast = head;
slow = head;
slow_par = head;
while(fast != NULL && fast->next != NULL){
fast = fast->next->next;
slow_par = slow;
slow = slow->next;
}
if(slow != slow_par)
slow_par->next = NULL;
TreeNode* root = new TreeNode(slow->val);
root->left = sortedListToBST(head);
root->right = sortedListToBST(slow->next);
return root;
}
};