Fork me on GitHub

Symmetric binary tree

问题

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

解决方案

思路:首先判断其根结点是否为空,然后判断左右结点是否对称,也就是左右结点是不是同时为空并且值相等

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
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)
{
if(pRoot == NULL)
{
return true ;
}
bool res = isTreeSymmetrical(pRoot->left,pRoot->right);
return res;
}

bool isTreeSymmetrical(TreeNode* pHead1,TreeNode* pHead2)
{
if(pHead1 == NULL && pHead2 == NULL)
{
return true;
}

if(pHead1 == NULL || pHead2 == NULL)
{
return false;
}
if((pHead1->val == pHead2->val))
{
return isTreeSymmetrical(pHead1->left,pHead2->right)&&isTreeSymmetrical(pHead1->right,pHead2->left);
}
return false;
}

};

本文标题:Symmetric binary tree

文章作者:LiuXiaoKun

发布时间:2018年10月09日 - 07:10

最后更新:2019年02月12日 - 23:02

原始链接:https://LiuZiQiao.github.io/2018/10/09/对称二叉树判断/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%