Data structure refresher: Day 12

 

Table of contents

 1. Flip the binary tree

 1. Recursion

Ideas and Algorithms

Complexity analysis

2. Total path

1. Breadth-first search

Complexity analysis

2. Recursion

Ideas and algorithms

Complexity analysis

 1. Flip the binary tree

226. Invert binary tree - LeetCode https://leetcode.cn/problems/invert-binary-tree/?plan=data-structures&plan_progress=ggfacv7

 1. Recursion

Ideas and Algorithms

This is a very classic binary tree problem. Obviously, we start from the root node, recursively traverse the tree, and start flipping from the leaf nodes first. If the left and right subtrees of the currently traversed node root have been flipped, then we only need to exchange the positions of the two subtrees to complete the flipping of the entire subtree with root as the root node.

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (root == nullptr) {
            return nullptr;
        }
        TreeNode* left = invertTree(root->left);
        TreeNode* right = invertTree(root->right);
        root->left = right;
        root->right = left;
        return root;
    }
};

Complexity analysis

Time complexity: O(N), where N is the number of binary tree nodes. We traverse each node in the binary tree, and for each node, we swap its two subtrees in constant time.

Space complexity: O(N). The space used is determined by the depth of the recursion stack, which is equal to the height of the current node in the binary tree. Under average circumstances, the height of a binary tree has a logarithmic relationship with the number of nodes, that is, O(logN). In the worst case, the tree forms a chain, and the space complexity is O(N).

2. Total path

112. Path sum - LeetCode https://leetcode.cn/problems/path-sum/?plan=data-structures&plan_progress=ggfacv7

Note that the requirement of this question is to ask whether the sum of the nodes on the path from the "root node" to a certain "leaf node" is equal to the target sum. The core idea is to traverse the tree once, and record the path sum from the root node to the current node during the traversal to prevent repeated calculations.

It is important to note that the given root may be empty.

1. Breadth-first search

First, we can think of using breadth-first search to record the path sum from the root node to the current node to prevent repeated calculations.

In this way, we use two queues to store the nodes to be traversed and the sum of the paths from the root node to these nodes.

class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum) {
        if (root == nullptr) {
            return false;
        }
        queue<TreeNode *> que_node;
        queue<int> que_val;
        que_node.push(root);
        que_val.push(root->val);
        while (!que_node.empty()) {
            TreeNode *now = que_node.front();
            int temp = que_val.front();
            que_node.pop();
            que_val.pop();
            if (now->left == nullptr && now->right == nullptr) {
                if (temp == sum) {
                    return true;
                }
                continue;
            }
            if (now->left != nullptr) {
                que_node.push(now->left);
                que_val.push(now->left->val + temp);
            }
            if (now->right != nullptr) {
                que_node.push(now->right);
                que_val.push(now->right->val + temp);
            }
        }
        return false;
    }
};

Complexity analysis

Time complexity: O(N), where N is the number of nodes in the tree. Visit each node once.

Space complexity: O(N), where N is the number of nodes in the tree. The space complexity mainly depends on the overhead of the queue. The number of elements in the queue will not exceed the number of nodes in the tree.

2. Recursion

Ideas and algorithms

Observing the function we are asked to complete, we can summarize its function: ask whether there is a path from the current node root to the leaf node, such that the sum of its paths is sum.

Assuming that the sum of the values ​​from the root node to the current node is val, we can transform this big problem into a small problem: whether there is a path from the child node of the current node to the leaf such that the sum of the paths is sum - val.

It is not difficult to find that this satisfies the recursive nature. If the current node is a leaf node, then we can directly determine whether sum is equal to val (because the path sum has been determined, which is the value of the current node, we only need to determine whether the path sum meets the conditions) . If the current node is not a leaf node, we only need to recursively ask its child nodes whether they can meet the conditions.

class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum) {
        if (root == nullptr) {
            return false;
        }
        if (root->left == nullptr && root->right == nullptr) {
            return sum == root->val;
        }
        return hasPathSum(root->left, sum - root->val) ||
               hasPathSum(root->right, sum - root->val);
    }
};

Complexity analysis

Time complexity: O(N), where N is the number of nodes in the tree. Visit each node once.

Space complexity: O(H), where H is the height of the tree. The space complexity mainly depends on the overhead of stack space during recursion. In the worst case, the tree appears in a chain shape and the space complexity is O(N). On average, the height of the tree is positively related to the logarithm of the number of nodes, and the space complexity is O(logN).

112. Path sum problem solution - LeetCode icon-default.png?t=M85Bhttps://leetcode.cn/problems/path-sum/solution/lu-jing-zong-he-de-si-chong-jie-fa-dfs-hui-su -bfs-/ Four solutions to path sum: DFS, backtracking, BFS, stack-path sum-LeetCode

Guess you like

Origin blog.csdn.net/m0_63309778/article/details/126860578