解题思路:
感觉这是一个栈,广搜,除去第一位,最后为0则对称
很好,很幼稚的想法。。。。很明显是错的
递归,怎么判断两边的子树对称呢?,两个指针,从根结点开始,一个左移另一个右移,一直相反向下走,分别遍历俩个子树,如完全一样,则可以判断这是一个对称二叉树。
代码:
/**
* 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 check(TreeNode *p, TreeNode *q) {
if (!p && !q) return true; // 若q,p都为nullptr,则返回true
if (!p || !q) return false; // 若左右俩指针一个是结点,一个不是结点
return p->val == q->val && check(p->left, q->right) && check(p->right, q->left);
}
bool isSymmetric(TreeNode* root) {
return check(root, root);
}
};
python:
# 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: TreeNode) -> bool:
if root is None:
return True
def check(p: TreeNode, q: TreeNode) ->bool:
if p is None and q is None:
return True
if p is None or q is None:
return False;
return p.val==q.val and check(p.left, q.right) and check(p.right, q.left)
return check(root.left, root.right)