代码随想录leetcode200题之二叉树

1 介绍

本博客用来记录代码随想录leetcode200题中二叉树部分的题目。

2 训练

题目1:递归遍历:中序、前序、后序

C++模板如下,

//中序
void traversal(TreeNode* cur, vector<int>& vec) {
    if (cur == NULL) return;
    traversal(cur->left, vec);  // 左
    vec.push_back(cur->val);    // 中
    traversal(cur->right, vec); // 右
}
//前序
void traversal(TreeNode* cur, vector<int>& vec) {
    if (cur == NULL) return;
    vec.push_back(cur->val);    // 中
    traversal(cur->left, vec);  // 左
    traversal(cur->right, vec); // 右
}
//后序
void traversal(TreeNode* cur, vector<int>& vec) {
    if (cur == NULL) return;
    traversal(cur->left, vec);  // 左
    traversal(cur->right, vec); // 右
    vec.push_back(cur->val);    // 中
}

题目2:迭代遍历:中序、前序、后序

C++模板如下,

这个迭代遍历的模板真是绝了!太精妙了!

//中序
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> result;
        stack<TreeNode*> st;
        if (root != NULL) st.push(root);
        while (!st.empty()) {
            TreeNode* node = st.top();
            if (node != NULL) {
                st.pop(); // 将该节点弹出,避免重复操作,下面再将右中左节点添加到栈中
                if (node->right) st.push(node->right);  // 添加右节点(空节点不入栈)

                st.push(node);                          // 添加中节点
                st.push(NULL); // 中节点访问过,但是还没有处理,加入空节点做为标记。

                if (node->left) st.push(node->left);    // 添加左节点(空节点不入栈)
            } else { // 只有遇到空节点的时候,才将下一个节点放进结果集
                st.pop();           // 将空节点弹出
                node = st.top();    // 重新取出栈中元素
                st.pop();
                result.push_back(node->val); // 加入到结果集
            }
        }
        return result;
    }
};
//前序
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> result;
        stack<TreeNode*> st;
        if (root != NULL) st.push(root);
        while (!st.empty()) {
            TreeNode* node = st.top();
            if (node != NULL) {
                st.pop();
                if (node->right) st.push(node->right);  // 右
                if (node->left) st.push(node->left);    // 左
                st.push(node);                          // 中
                st.push(NULL);
            } else {
                st.pop();
                node = st.top();
                st.pop();
                result.push_back(node->val);
            }
        }
        return result;
    }
};
//后序
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> result;
        stack<TreeNode*> st;
        if (root != NULL) st.push(root);
        while (!st.empty()) {
            TreeNode* node = st.top();
            if (node != NULL) {
                st.pop();
                st.push(node);                          // 中
                st.push(NULL);

                if (node->right) st.push(node->right);  // 右
                if (node->left) st.push(node->left);    // 左

            } else {
                st.pop();
                node = st.top();
                st.pop();
                result.push_back(node->val);
            }
        }
        return result;
    }
};

题目3:层序遍历

C++模板如下,

//使用队列queue实现
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        queue<TreeNode*> que;
        if (root != NULL) que.push(root);
        vector<vector<int>> result;
        while (!que.empty()) {
            int size = que.size();
            vector<int> vec;
            // 这里一定要使用固定大小size,不要使用que.size(),因为que.size是不断变化的
            for (int i = 0; i < size; i++) {
                TreeNode* node = que.front();
                que.pop();
                vec.push_back(node->val);
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
            result.push_back(vec);
        }
        return result;
    }
};
//使用递归实现(极其罕见,一般不这样写)
class Solution {
public:
    void order(TreeNode* cur, vector<vector<int>>& result, int depth)
    {
        if (cur == nullptr) return;
        if (result.size() == depth) result.push_back(vector<int>());
        result[depth].push_back(cur->val);
        order(cur->left, result, depth + 1);
        order(cur->right, result, depth + 1);
    }
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> result;
        int depth = 0;
        order(root, result, depth);
        return result;
    }
};

相关题目有:

  1. 102. 二叉树的层序遍历
  2. 107. 二叉树的层序遍历 II
  3. 199. 二叉树的右视图
  4. 637. 二叉树的层平均值
  5. 429. N 叉树的层序遍历
  6. 515. 在每个树行中找最大值
  7. 116. 填充每个节点的下一个右侧节点指针
  8. 117. 填充每个节点的下一个右侧节点指针 II
  9. 104. 二叉树的最大深度
  10. 111. 二叉树的最小深度

题目4226. 翻转二叉树

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (root == nullptr) return root;

        if (root->left) invertTree(root->left);
        if (root->right) invertTree(root->right);

        TreeNode* t = root->left;
        root->left = root->right;
        root->right = t;
        return root; 
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root is None:
            return root 
        if root.left:
            self.invertTree(root.left)
        if root.right:
            self.invertTree(root.right)
        root.left, root.right = root.right, root.left 
        return root 

题目5101. 对称二叉树

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if (root == nullptr) return true;

        function<bool(TreeNode*,TreeNode*)> check =[&](TreeNode* left, TreeNode* right) -> bool {
            if (left == nullptr && right == nullptr) return true;
            else if (left == nullptr || right == nullptr) return false;

            if (left->val != right->val) return false;
            return check(left->left, right->right) && check(left->right, right->left);
        };

        return check(root->left, root->right);
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        if root is None:
            return True 
        
        def check(left: TreeNode, right: TreeNode) -> bool:
            if left is None and right is None:
                return True 
            elif left is None or right is None:
                return False 
            
            if left.val != right.val:
                return False 
            
            return check(left.right, right.left) and check(left.left, right.right)
        
        return check(root.left, root.right)

题目6104. 二叉树的最大深度

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == nullptr) return 0;
        int d1 = maxDepth(root->left);
        int d2 = maxDepth(root->right);
        return max(d1,d2) + 1;
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if root is None:
            return 0
        
        d1 = self.maxDepth(root.left)
        d2 = self.maxDepth(root.right)
        d = max(d1, d2) + 1
        return d 

题目7111. 二叉树的最小深度

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
        if (root == nullptr) return 0;
        int d1 = minDepth(root->left);
        int d2 = minDepth(root->right);
        if (root->left == nullptr and root->right != nullptr) return d2 + 1;
        if (root->left != nullptr and root->right == nullptr) return d1 + 1;
        return min(d1,d2)+1;
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        if root is None:
            return 0
        
        d1 = self.minDepth(root.left)
        d2 = self.minDepth(root.right)

        if root.left is None and root.right is not None:
            return 1 + d2 
        
        if root.left is not None and root.right is None:
            return d1 + 1
        
        return min(d1, d2) + 1

题目8222. 完全二叉树的节点个数

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int countNodes(TreeNode* root) {
        if (root == nullptr) return 0;
        int ldepth = 0, rdepth = 0;
        TreeNode *lnode = root, *rnode = root;
        while (lnode != nullptr) {
            ldepth += 1;
            lnode = lnode->left;
        }
        while (rnode != nullptr) {
            rdepth += 1;
            rnode = rnode->right;
        }
        if (ldepth == rdepth) return (1 << ldepth) - 1;
        return 1 + countNodes(root->left) + countNodes(root->right);
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        #对于完全二叉树,如果不是满的,一直递归左子树和右子树,一定会存在它们为满二叉树的情况
        if root is None:
            return 0
        ldepth, lnode = 0, root
        rdepth, rnode = 0, root
        while lnode:
            ldepth += 1
            lnode = lnode.left 
        while rnode:
            rdepth += 1
            rnode = rnode.right
        if ldepth == rdepth:
            return (1 << ldepth) - 1
        return self.countNodes(root.left) + self.countNodes(root.right) + 1
        

题目9110. 平衡二叉树

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if (root == nullptr) return true;

        function<int(TreeNode*)> get_depth =[&](TreeNode* node) -> int {
            if (node == nullptr) return 0;
            int d1 = get_depth(node->left);
            int d2 = get_depth(node->right);
            return max(d1,d2)+1;
        };

        int d1 = get_depth(root->left);
        int d2 = get_depth(root->right);

        if (abs(d1-d2) >= 2) return false;
        return isBalanced(root->left) && isBalanced(root->right);
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        if root is None:
            return True 
        
        def get_depth(node: TreeNode) -> int:
            if node is None:
                return 1
            d1 = get_depth(node.left)
            d2 = get_depth(node.right)
            return max(d1,d2) + 1
        
        d1 = get_depth(root.left)
        d2 = get_depth(root.right)

        if abs(d1-d2) >= 2:
            return False
        
        return self.isBalanced(root.left) and self.isBalanced(root.right)
        

题目10257. 二叉树的所有路径

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<string> res;
    vector<int> cur; 

    void dfs(TreeNode* node) {
        if (node->left == nullptr && node->right == nullptr) {
            cur.emplace_back(node->val);
            string ans = to_string(cur[0]);
            for (int i = 1; i < cur.size(); ++i) ans += "->" + to_string(cur[i]);
            res.emplace_back(ans);
            cur.pop_back();
            return;
        }

        cur.emplace_back(node->val);
        if (node->left) dfs(node->left);
        if (node->right) dfs(node->right);

        cur.pop_back();
        return;
    }

    vector<string> binaryTreePaths(TreeNode* root) {
        dfs(root);
        return res;
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        res = []
        cur = []
        def dfs(node: TreeNode) -> None:
            if node.left is None and node.right is None:
                res.append(copy.deepcopy(cur + [str(node.val)]))
                return
            cur.append(str(node.val))
            if node.left:
                dfs(node.left)
            if node.right:
                dfs(node.right)
            del cur[-1]
            return 
        dfs(root)
        res = ["->".join(path) for path in res]
        return res

题目11404. 左叶子之和

C++代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int dfs(TreeNode* node, bool left) {
        if (node == nullptr) return 0;
        if (node->left == nullptr && node->right == nullptr && left) return node->val;
        return dfs(node->left, true) + dfs(node->right, false);
    }

    int sumOfLeftLeaves(TreeNode* root) {  
        return dfs(root, false);
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
        def dfs(node: TreeNode, left: bool) -> int:
            if node is None:
                return 0
            
            if node.left is None and node.right is None and left:
                return node.val 
            
            return dfs(node.left, True) + dfs(node.right, False)
        
        
        return dfs(root, False)
            

题目12513. 找树左下角的值

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        int res = 0;
        queue<TreeNode*> q;
        if (root) q.push(root);
        while (!q.empty()) {
            int ns = q.size();
            for (int i = 0; i < ns; ++i) {
                auto t = q.front();
                q.pop();
                if (i == 0) res = t->val;
                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);
            }
        }
        return res;
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        res = 0
        q = collections.deque()
        if root:
            q.append(root)
        while len(q) > 0:
            ns = len(q)
            for i in range(ns):
                t = q.popleft()
                if i == 0:
                    res = t.val 
                if t.left:
                    q.append(t.left)
                if t.right:
                    q.append(t.right)
            
        return res

题目13112. 路径总和

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool dfs(TreeNode* node, int s, int targetSum) {
        if (node == nullptr) return false;
        if (node->left == nullptr && node->right == nullptr) {
            if (s + node->val == targetSum) return true;
            else return false;
        }
        s += node->val;
        bool t = false;
        if (node->left) t |= dfs(node->left, s, targetSum);
        if (node->right) t |= dfs(node->right, s, targetSum);
        s -= node->val;
        return t;
    }

    bool hasPathSum(TreeNode* root, int targetSum) {
        return dfs(root, 0, targetSum);
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        def dfs(node: TreeNode, s: int) -> bool:
            nonlocal targetSum

            if node is None:
                return False 
            
            if node.left is None and node.right is None:
                if s + node.val == targetSum:
                    return True 
                else:
                    return False 

            s += node.val
            t = False
            if node.left:
                t = t or dfs(node.left, s)
            if node.right:
                t = t or dfs(node.right, s)
            s -= node.val 
            return t 
        
        return dfs(root, 0)
            

题目14106. 从中序与后序遍历序列构造二叉树

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int n = inorder.size();
        if (n == 0) return nullptr;
        int i = 0;
        set<int> left;
        while (inorder[i] != postorder.back()) {
            left.insert(inorder[i]);
            i++;
        }
        int j = 0;
        while (left.count(postorder[j]) != 0) {
            j += 1;
        }
        TreeNode *node = new TreeNode(postorder.back());
        vector<int> left_inorder;
        vector<int> right_inorder;
        for (int k = 0; k < i; ++k) left_inorder.emplace_back(inorder[k]);
        for (int k = i + 1; k < n; ++k) right_inorder.emplace_back(inorder[k]);
        vector<int> left_postorder;
        vector<int> right_postorder;
        for (int k = 0; k < j; ++k) left_postorder.emplace_back(postorder[k]);
        for (int k = j; k < n - 1; ++k) right_postorder.emplace_back(postorder[k]);

        node->left = buildTree(left_inorder, left_postorder);
        node->right = buildTree(right_inorder, right_postorder);
        return node;
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        n = len(inorder)
        if n == 0:
            return None 
        node = TreeNode()
        node.val = postorder[-1]
        i = 0
        left = set()
        while inorder[i] != node.val:
            left.add(inorder[i])
            i += 1
        j = 0
        while postorder[j] in left:
            j += 1
        node.left = self.buildTree(inorder[0:i], postorder[0:j])
        node.right = self.buildTree(inorder[i+1:], postorder[j:-1])
        return node 
        

题目15654. 最大二叉树

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        int n = nums.size();
        if (n == 0) return nullptr;
        int i = 0;
        int maxv = INT_MIN;
        for (int k = 0; k < n; ++k) {
            if (nums[k] > maxv) {
                maxv = nums[k];
                i = k;
            }
        }
        vector<int> left;
        vector<int> right;
        for (int k = 0; k < i; ++k) left.emplace_back(nums[k]);
        for (int k = i + 1; k < n; ++k) right.emplace_back(nums[k]);
        TreeNode *node = new TreeNode(maxv);
        node->left = constructMaximumBinaryTree(left);
        node->right = constructMaximumBinaryTree(right);
        return node;
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
        n = len(nums)
        if n == 0:
            return None 
        maxv = max(nums)
        i = 0
        while nums[i] != maxv:
            i += 1
        
        node = TreeNode()
        node.val = maxv 
        
        node.left = self.constructMaximumBinaryTree(nums[0:i])
        node.right = self.constructMaximumBinaryTree(nums[i+1:])
        return node 

题目16617. 合并二叉树

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
        if (root1 == nullptr && root2 == nullptr) return nullptr;
        else if (root1 == nullptr || root2 == nullptr) {
            return root1 == nullptr ? root2 : root1;
        }

        root1->val += root2->val;
        root1->left = mergeTrees(root1->left, root2->left);
        root1->right = mergeTrees(root1->right, root2->right);
        return root1;
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
        if root1 is None and root2 is None:
            return None 
        elif root1 is None or root2 is None:
            return root1 if root2 is None else root2 
        
        root1.val += root2.val 

        root1.left = self.mergeTrees(root1.left, root2.left)
        root1.right = self.mergeTrees(root1.right, root2.right)

        return root1 

题目17700. 二叉搜索树中的搜索

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* searchBST(TreeNode* root, int val) {
        if (root == nullptr) return nullptr;
        if (root->val > val) return searchBST(root->left, val);
        else if (root->val < val) return searchBST(root->right, val);
        else return root;
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        if root is None:
            return None 
        
        if root.val > val:
            return self.searchBST(root.left, val)
        elif root.val < val:
            return self.searchBST(root.right, val)
        else:
            return root 

题目1898. 验证二叉搜索树

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    TreeNode *pre = nullptr;
public:
    bool isValidBST(TreeNode* root) {
        if (root == nullptr) return true;
        bool left = isValidBST(root->left);
        if (pre != nullptr && pre->val >= root->val) return false;
        pre = root;
        bool right = isValidBST(root->right);
        return left && right;
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def __init__(self):
        self.pre = None

    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        if root is None:
            return True 
        
        left = self.isValidBST(root.left)
        if self.pre is not None and self.pre.val >= root.val:
            return False
        self.pre = root 
        right = self.isValidBST(root.right)

        return left and right

题目19530. 二叉搜索树的最小绝对差

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    TreeNode *pre = nullptr;
public:
    int getMinimumDifference(TreeNode* root) {
        int res = INT_MAX;
        if (root == nullptr) return res;
        int left = getMinimumDifference(root->left);
        if (pre != nullptr) {
            res = min(res, abs(pre->val - root->val));
        }
        pre = root;
        int right = getMinimumDifference(root->right);
        res = min(res, left);
        res = min(res, right);
        return res;
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def __init__(self):
        self.pre = None 

    def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
        res = int(1e20)
        if root is None:
            return res 
        res = min(res, self.getMinimumDifference(root.left))
        if self.pre is not None:
            res = min(res, abs(self.pre.val - root.val))
        self.pre = root 
        res = min(res, self.getMinimumDifference(root.right))
        return res
        

题目20501. 二叉搜索树中的众数

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    vector<int> res = {};
    int cnt = 1;
    int maxcnt = 1;
    TreeNode *pre = nullptr;
public:
    void dfs(TreeNode *cur) {
        if (cur == nullptr) return;
        dfs(cur->left);

        if (pre == nullptr) cnt = 1;
        else if (pre->val == cur->val) cnt += 1;
        else cnt = 1;

        pre = cur;

        if (cnt == maxcnt) res.emplace_back(cur->val);

        if (cnt > maxcnt) {
            maxcnt = cnt;
            res.clear();
            res.emplace_back(cur->val);
        }

        dfs(cur->right);
        return;
    }

    vector<int> findMode(TreeNode* root) {
        dfs(root);
        return res;
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def __init__(self):
        self.pre = None 
        self.maxcnt = 1
        self.cnt = 1
        self.res = []

    def dfs(self, node)-> None:
        if node is None:
            return 
        self.dfs(node.left)
        if self.pre is None:
            self.cnt = 1
        elif self.pre.val == node.val: 
            self.cnt += 1
        else:
            self.cnt = 1
        self.pre = node
        
        if self.cnt == self.maxcnt:
            self.res.append(node.val)
        
        if self.cnt > self.maxcnt:
            self.maxcnt = self.cnt 
            self.res = [node.val]
        
        self.dfs(node.right)
        return

    def findMode(self, root: Optional[TreeNode]) -> List[int]:
        self.dfs(root)
        return self.res


题目21236. 二叉树的最近公共祖先

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root == p || root == q || root == nullptr) return root;
        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);
        if (left != nullptr && right != nullptr) return root;
        else return left == nullptr ? right : left;
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if root == p or root == q or root is None:
            return root 
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)
        if left is not None and right is not None:
            return root 
        else:
            return left if (left is not None) else right 

题目22235. 二叉搜索树的最近公共祖先

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root == p || root == q || root == nullptr) return root;
        if ((p->val < root->val && q->val > root->val) || (p->val > root->val && q->val < root->val)) return root;
        else if (p->val < root->val && q->val < root->val) return lowestCommonAncestor(root->left, p, q);
        else if (p->val > root->val && q->val > root->val) return lowestCommonAncestor(root->right, p, q);
        return nullptr;
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if root == p or root == q or root == None:
            return root 
        
        if p.val < root.val < q.val or p.val > root.val > q.val:
            return root 
        elif p.val < root.val and q.val < root.val:
            return self.lowestCommonAncestor(root.left, p, q)
        elif p.val > root.val and q.val > root.val:
            return self.lowestCommonAncestor(root.right, p, q)
        
        

题目23701. 二叉搜索树中的插入操作

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if (root == nullptr) {
            TreeNode *node = new TreeNode(val);
            return node;
        }
        if (root->val > val) root->left = insertIntoBST(root->left, val);
        else if (root->val < val) root->right = insertIntoBST(root->right, val);
        return root;
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        if root is None:
            node = TreeNode(val)
            return node 
        if root.val > val:
            root.left = self.insertIntoBST(root.left, val)
        elif root.val < val:
            root.right = self.insertIntoBST(root.right, val)
        return root

题目24450. 删除二叉搜索树中的节点

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* deleteNode(TreeNode* root, int key) {
        if (root == nullptr) return nullptr;

        if (root->val == key) {
            if (root->left == nullptr && root->right == nullptr) return nullptr;
            else if (root->left == nullptr) {
                auto node = root->right;
                delete root;
                return node;
            } else if (root->right == nullptr) {
                auto node = root->left;
                delete root;
                return node;
            } else {
                TreeNode* t = root->right;
                while (t->left != nullptr) t = t->left;
                t->left = root->left;
                auto node = root->right;
                delete root;
                return node; 
            }
        }

        if (root->val < key) root->right = deleteNode(root->right, key);
        if (root->val > key) root->left = deleteNode(root->left, key);
        return root;
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
        if root is None:
            return root 
        
        if root.val == key:
            if root.left is None and root.right is None:
                return None  
            elif root.left is None:
                return root.right
            elif root.right is None:
                return root.left 
            else:
                t = root.right 
                while t.left is not None:
                    t = t.left 
                t.left = root.left 
                return root.right  

        if root.val > key:
            root.left = self.deleteNode(root.left, key) 
        if root.val < key:
            root.right = self.deleteNode(root.right, key)
        return root 

题目25669. 修剪二叉搜索树

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* trimBST(TreeNode* root, int low, int high) {
        if (root == nullptr) return nullptr;

        if (root->val < low) return trimBST(root->right, low, high);
        else if (root->val > high) return trimBST(root->left, low, high);
        else {
            root->left = trimBST(root->left, low, high);
            root->right = trimBST(root->right, low, high);
        }
        return root;
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
        if root is None:
            return None 
        
        if root.val < low:
            return self.trimBST(root.right, low, high)
        elif root.val > high:
            return self.trimBST(root.left, low, high)
        else:
            root.left = self.trimBST(root.left, low, high)
            root.right = self.trimBST(root.right, low, high)
        return root 
        

题目26108. 将有序数组转换为二叉搜索树

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        int n = nums.size();
        if (n == 0) return nullptr;
        int idx = n / 2;
        TreeNode *root = new TreeNode(nums[idx]);
        vector<int> left;
        vector<int> right;
        for (int i = 0; i < idx; ++i) left.emplace_back(nums[i]);
        for (int i = idx + 1; i < n; ++i) right.emplace_back(nums[i]);
        root->left = sortedArrayToBST(left);
        root->right = sortedArrayToBST(right);
        return root;
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:    
        n = len(nums)
        if n == 0:
            return None 
        idx = n // 2
        root = TreeNode(nums[idx])
        root.left = self.sortedArrayToBST(nums[0:idx])
        root.right = self.sortedArrayToBST(nums[idx+1:])
        return root 

题目27538. 把二叉搜索树转换为累加树

C++代码如下,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    int s = 0;
public:
    TreeNode* convertBST(TreeNode* root) {
        if (root == nullptr) return nullptr;
        convertBST(root->right);
        s += root->val;
        root->val = s;
        convertBST(root->left);
        return root;
    }
};

python3代码如下,

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def __init__(self):
        self.s = 0

    def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root is None:
            return None 
        self.convertBST(root.right)
        self.s += root.val 
        root.val = self.s 
        self.convertBST(root.left)
        return root 

3 参考

代码随想录官网

  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YMWM_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值