LeetCode简单题:101. 对称二叉树(Python,C++,Java)

一.解法

https://leetcode-cn.com/problems/symmetric-tree/
要点:递归,树
Python,C++,Java都用了相同的递归方法
实现这样一个递归函数,通过同步移动两个指针的方法来遍历这棵树,p 指针和 q 指针一开始都指向这棵树的根,随后 p 右移时,q 左移,p 左移时,q 右移。每次检查当前 p 和 q 节点的值是否相等,如果相等再判断左右子树是否对称。

二.Python实现

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

class Solution:

    def isSymmetric(self, root: TreeNode) -> bool:
        def help_1(root):
            return [root.val] + help_1(root.left) + help_1(root.right) if root else ['null']
        def help_2(root):
            return [root.val] + help_2(root.right) +  help_2(root.left) if root else ['null']
        return help_2(root) == help_1(root)

三.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:
    bool isSymmetric(TreeNode* root) {
        TreeNode* root_p=root;
        return is_sym(root,root_p);
    }
    bool is_sym(TreeNode* root, TreeNode* root_p){
        if(!root&&!root_p)
            return true;
        if(!root||!root_p||root->val!=root_p->val)
            return false;
        return is_sym(root->left,root_p->right)&&is_sym(root->right,root_p->left);
    }
};

四.java实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        return check(root, root);
    }

    public boolean check(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {
            return false;
        }
        return p.val == q.val && check(p.left, q.right) && check(p.right, q.left);
    }
}

你可能感兴趣的:(LeetCode简单题:101. 对称二叉树(Python,C++,Java))