Bootstrap

算法训练营打卡Day14

目录

题目1.226.翻转二叉树

题目2.101. 对称二叉树

题目1.226.翻转二叉树

力扣题目链接(opens new window)

听说一位巨佬面Google被拒了,因为没写出翻转二叉树 | LeetCode:226.翻转二叉树_哔哩哔哩_bilibili

翻转一棵二叉树。

Python

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if not root:
            return None
        root.left, root.right = root.right, root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root

C

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* invertTree(struct TreeNode* root) {
    if (root == NULL){
        return root;
    }
    struct TreeNode* temp = root->right;
    root->right = root->left;
    root->left = temp;
    invertTree(root->left);
    invertTree(root->right);
    return root;
}

题目2.101. 对称二叉树

力扣题目链接(opens new window)
新学期要从学习二叉树开始! | LeetCode:101. 对称二叉树_哔哩哔哩_bilibili

相似题目:

给定一个二叉树,检查它是否是镜像对称的。

Python

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if not root:
            return True
        return self.compare(root.left, root.right)
        
    def compare(self, left, right):
        #首先排除空节点的情况
        if left == None and right != None: return False
        elif left != None and right == None: return False
        elif left == None and right == None: return True
        #排除了空节点,再排除数值不相同的情况
        elif left.val != right.val: return False
        
        #此时就是:左右节点都不为空,且数值相同的情况
        #此时才做递归,做下一层的判断
        outside = self.compare(left.left, right.right) #左子树:左、 右子树:右
        inside = self.compare(left.right, right.left) #左子树:右、 右子树:左
        isSame = outside and inside #左子树:中、 右子树:中 (逻辑处理)
        return isSame

C

public bool IsSymmetric(TreeNode root)
{
    if (root == null) return true;
    return Compare(root.left, root.right);
}
public bool Compare(TreeNode left, TreeNode right)
{
    if(left == null && right != null) return false;
    else if(left != null && right == null ) return false;
    else if(left == null && right == null) return true;
    else if(left.val != right.val) return false;

    var outside = Compare(left.left, right.right);
    var inside = Compare(left.right, right.left);

    return outside&&inside;
}

总结:解法只涉及到递归法,进阶的解法可以参考迭代法,难点在于理解递归的三步骤,考虑遍历的方式,是前中后遍历的哪一种,使用层序遍历等。

未完待续~

;