101. Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / \ 2 2 \ \ 3 3
代码如下:
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
43
44
45
46
47
48
49
50
51
52
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//思路:
//1.判断root是否为空,若空则返回true,否则false;
//2.判断root->left,root->right是否同时为空,若为空则返回true;
//3.判断root->left,root->right同时不为空时,将root->right反转,
//然后判断新root->right和root->left是否为相同的树。
class
Solution {
public
:
bool
isSameTree(TreeNode* p, TreeNode* q) {
bool
childResult;
if
( NULL == p && NULL == q)
return
true
;
if
( NULL != p && NULL != q && p->val == q->val)
{
return
childResult = isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}
return
false
;
}
void
reverseTree(TreeNode* root)
{
if
(!root)
return
;
TreeNode *p,*q;
p = root->left;
q = root->right;
root->left = q;
root->right = p;
reverseTree(root->left);
reverseTree(root->right);
}
bool
isSymmetric(TreeNode* root) {
if
( (NULL == root) || ( NULL == root->left && NULL == root->right) )
return
true
;
if
(NULL != root->left && NULL != root->right)
{
reverseTree(root->right);
return
isSameTree(root->left,root->right);
}
return
false
;
}
};
|
本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1835171