Skip to content
Rain Hu's Workspace
Go back

[Algo] 0-4. 二叉樹(Binary Tree)

Rain Hu

一、二叉樹的思維模式

[LeetCode. 104] Maximum Depth of Binary Tree(Easy)

int depth = 0;
int maxDepth(TreeNode* root){
    traverse(root, 1);
    return depth;
}
void traverse(TreeNode* root, int currDepth){
    if (!root) return;
    traverse(root->left, currDepth+1);
    depth = max(depth, currDepth);
    traverse(root->right, currDepth+1);
}
int maxDepth(TreeNode* root) {
    if (root == NULL) return 0;
    return 1 + max(maxDepth(root->left), maxDepth(root->right));
}

二、前序、中序、後序

quick sort

void sort(vector<int>& nums, int left, int right){
    if (left >= right) return;              // 終止條件
    int mid = partition(nums, left, right); // 做什麼事(pre-order)
    sort(nums, left, mid-1);                // 左子樹
    sort(nums, mid+1, right);               // 右子樹
}
int partition(vector<int>& nums, int left, int right){
    int pivot = right;
    while (left < right){
        while (nums[left] < nums[pivot]) left++;
        while (nums[right] > nums[pivot]) right--;
        if (left < right) swap(nums[left], nums[right]);
    }
    if (left == right && nums[left] > nums[pivot] || nums[right] < nums[pivot]){
        swap(nums[left], pivot);
        return left;
    }
    return pivot;
}

merge sort

void sort(vector<int>& nums, int left, int right){
    if (right <= left) return;              // 終止條件
    int mid = left + (right-left)/2;
    sort(nums, left, mid);                  // 左子樹
    sort(nums, mid+1, right);               // 右子樹
    merge(nums, left, mid, right);          // 做什麼事(post-order)
}
void merge(vector<int>& nums, int left, int mid, int right){
    vector<int> vec;
    int i = left, j = mid+1;
    while (i <= mid && j <= right){
        int x = nums[i] < nums[j] ? nums[i++] : nums[j++];
        vec.push_back(x);
    }
    while (i <= mid) vec.push_back(nums[i++]);
    while (j <= right) vec.push_back(nums[j++]);
    for (int i = left; i <= right; i++)
        nums[i] = vec[i-left];
}

三、層序遍歷(level-order)

void traverse(TreeNode* root){
    queue<TreeNode*> q;
    q.push(root);
    while (!q.empty()){
        int sz = q.size();
        while (sz--){
            TreeNode* curr = q.front();
            q.pop();
            // operation
            if (curr->left) q.push(curr->left);
            if (curr->right) q. push(curr->right);
        }
    }
}


Share this post on:

Previous
[Algo] 0-1. 複雜度分析 Algorithmic complexity / Big-O / Asymptotic analysis
Next
[Algo] 0-3. 鏈表(Linked List)