第7周 数据结构-树

二叉树的最近公共祖先
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) {
        /*
        思路:先求出p,q的深度,求深度的过程中记录下各个节点的父节点,得到深度后先使得p,q到同一深度,然后在一起往上走直到走到公共祖先
        时间复杂度:O(n)
        空间复杂度:O(n)
        */
        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) {
        /*
        思路:递归构造子树,取nums中间的值做根节点,中间值左右的子序列用于构造左右子树
        时间复杂度:O(n)
        空间复杂度:O(n)
        */
        return build(nums, 0, nums.size()-1);
    }
};
根据有序链表构造平衡的二叉查找树
class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        /*
        思路:快慢指针找中间节点,然后递归调用BST构造函数。需注意找到中间节点后要断开链表
        时间复杂度:O(n)
        空间复杂度:O(n)
        */
        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;      
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值