对称二叉树
题目
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
思路:
递归边界:
(1)都为空指针则返回 true
(2)只有一个为空则返回 false
(3)两个指针当前节点值不相等 返回false
递归过程:
(1)判断 A 的右子树与 B 的左子树是否对称
(2)判断 A 的左子树与 B 的右子树是否对称
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) {
bool res = true;
if(root)
res = judge(root->left, root->right);
return res;
}
private:
bool judge(TreeNode* A, TreeNode* B)
{
if(A==nullptr && B==nullptr)
return true;
if(A==nullptr || B==nullptr)
return false;
if(A->val!=B->val)
return false;
return judge(A->left, B->right) && judge(A->right, B->left);
}
};
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 judge(A: TreeNode, B: TreeNode) -> bool:
if A==None and B==None:
return True
if A==None or B==None:
return False
if A.val != B.val:
return False
return judge(A.left, B.right) and judge(A.right, B.left)
res = True
if root:
res = judge(root.left, root.right)
return res