題目描述
請實現一個函數,用來判斷一顆二叉樹是不是對稱的。注意,如果一個二叉樹同此二叉樹的鏡像是同樣的,定義其爲對稱的。
思路:首先根節點以及其左右子樹,左子樹的左子樹和右子樹的右子樹相同
- 左子樹的右子樹和右子樹的左子樹相同即可,採用遞歸
- 非遞歸也可,採用棧或隊列存取各級子樹根節點
python
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetrical(self, pRoot):
# write code here
def is_same(p1,p2):
if not p1 and not p2:
return True
if (p1 and p2) and p1.val==p2.val:
return is_same(p1.left,p2.right) and is_same(p1.right,p2.left)
return False
if not pRoot:
return True
if pRoot.left and not pRoot.right:
return False
if not pRoot.left and pRoot.right:
return False
return is_same(pRoot.left,pRoot.right)
c++
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
bool isSymmetrical(TreeNode* pRoot)
{
return isSymmetrical(pRoot,pRoot);
}
bool isSymmetrical(TreeNode* pRoot1,TreeNode* pRoot2)
{
if(pRoot1==nullptr&&pRoot2==nullptr)
return true;
if(pRoot1==nullptr||pRoot2==nullptr)
return false;
if(pRoot1->val!=pRoot2->val)
return false;
return isSymmetrical(pRoot1->left,pRoot2->right)&& isSymmetrical(pRoot1->right,pRoot2->left);
}
};