++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

给定一个二叉树,判断是否他自己的镜像对称的。(以自身中间,为镜像对称的)

例如羡慕这个二叉树就是对称的:

    1
/ \
2 2
/ \ / \
3 4 4 3

但是下面这个就不是对称的:

    1
/ \
2 2
\ \
3 3

笔记:

如果你既能迭代的解决这个问题,又能递归的解决这个问题,那么将给你加分。

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
/ \
2 2
/ \ / \
3 4 4 3

But the following is not:

    1
/ \
2 2
\ \
3 3

Note:
Bonus points if you could solve it both recursively and iteratively.

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
test.cpp:
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
 
#include <iostream>
#include <cstdio>
#include <stack>
#include <vector>
#include "BinaryTree.h"

using namespace std;

/**
 * Definition for binary tree
 * struct TreeNode {
 * int val;
 * TreeNode *left;
 * TreeNode *right;
 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

bool isSymmetric(TreeNode *left, TreeNode *right)
{
    if (!left && !right)
    {
        return true;
    }
    if (!left || !right)
    {
        return false;
    }
    return left->val == right->val && isSymmetric(left->left, right->right)
           && isSymmetric(left->right, right->left);
}

bool isSymmetric(TreeNode *root)
{
    return root ? isSymmetric(root->left, root->right) : true;
}

// 树中结点含有分叉,
//                  6
//              /       \
//             7         2
//           /   \
//          1     4
//               / \
//              3   5
int main()
{
    TreeNode *pNodeA1 = CreateBinaryTreeNode(6);
    TreeNode *pNodeA2 = CreateBinaryTreeNode(7);
    TreeNode *pNodeA3 = CreateBinaryTreeNode(2);
    TreeNode *pNodeA4 = CreateBinaryTreeNode(1);
    TreeNode *pNodeA5 = CreateBinaryTreeNode(4);
    TreeNode *pNodeA6 = CreateBinaryTreeNode(3);
    TreeNode *pNodeA7 = CreateBinaryTreeNode(5);

ConnectTreeNodes(pNodeA1, pNodeA2, pNodeA3);
    ConnectTreeNodes(pNodeA2, pNodeA4, pNodeA5);
    ConnectTreeNodes(pNodeA5, pNodeA6, pNodeA7);

// 树中结点含有分叉,
    //                  1
    //              /       \
    //             2         2
    //           /   \       / \
    //          3     4     4   3

TreeNode *pNodeB1 = CreateBinaryTreeNode(1);
    TreeNode *pNodeB2 = CreateBinaryTreeNode(2);
    TreeNode *pNodeB3 = CreateBinaryTreeNode(2);
    TreeNode *pNodeB4 = CreateBinaryTreeNode(3);
    TreeNode *pNodeB5 = CreateBinaryTreeNode(4);
    TreeNode *pNodeB6 = CreateBinaryTreeNode(4);
    TreeNode *pNodeB7 = CreateBinaryTreeNode(3);

ConnectTreeNodes(pNodeB1, pNodeB2, pNodeB3);
    ConnectTreeNodes(pNodeB2, pNodeB4, pNodeB5);
    ConnectTreeNodes(pNodeB3, pNodeB6, pNodeB7);

bool ans = isSymmetric(pNodeA1);

if (ans == true)
    {
        cout << "Symmetric Tree!" << endl;
    }
    else
    {
        cout << "Not Symmetric Tree!" << endl;
    }

bool ans1 = isSymmetric(pNodeB1);

if (ans1 == true)
    {
        cout << "Symmetric Tree!" << endl;
    }
    else
    {
        cout << "Not Symmetric Tree!" << endl;
    }
    DestroyTree(pNodeA1);
    DestroyTree(pNodeB1);
    return 0;
}

结果输出:
Not Symmetric Tree!
Symmetric 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
 
#include <iostream>
#include <cstdio>
#include <stack>
#include <vector>
#include "BinaryTree.h"

using namespace std;

/**
 * Definition for binary tree
 * struct TreeNode {
 * int val;
 * TreeNode *left;
 * TreeNode *right;
 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
bool isSymmetric(TreeNode *root)
{
    if (!root)
    {
        return true;
    }
    stack<TreeNode *> s;
    s.push(root->left);
    s.push(root->right);

TreeNode *p, *q;
    while (!s.empty())
    {
        p = s.top();
        s.pop();
        q = s.top();
        s.pop();

if (!p && !q)
        {
            continue;
        }
        if (!p || !q)
        {
            return false;
        }
        if (p->val != q->val)
        {
            return false;
        }

s.push(p->left);
        s.push(q->right);

s.push(p->right);
        s.push(q->left);
    }
    return true;
}

// 树中结点含有分叉,
//                  6
//              /       \
//             7         2
//           /   \
//          1     4
//               / \
//              3   5
int main()
{
    TreeNode *pNodeA1 = CreateBinaryTreeNode(6);
    TreeNode *pNodeA2 = CreateBinaryTreeNode(7);
    TreeNode *pNodeA3 = CreateBinaryTreeNode(2);
    TreeNode *pNodeA4 = CreateBinaryTreeNode(1);
    TreeNode *pNodeA5 = CreateBinaryTreeNode(4);
    TreeNode *pNodeA6 = CreateBinaryTreeNode(3);
    TreeNode *pNodeA7 = CreateBinaryTreeNode(5);

ConnectTreeNodes(pNodeA1, pNodeA2, pNodeA3);
    ConnectTreeNodes(pNodeA2, pNodeA4, pNodeA5);
    ConnectTreeNodes(pNodeA5, pNodeA6, pNodeA7);

// 树中结点含有分叉,
    //                  1
    //              /       \
    //             2         2
    //           /   \       / \
    //          3     4     4   3

TreeNode *pNodeB1 = CreateBinaryTreeNode(1);
    TreeNode *pNodeB2 = CreateBinaryTreeNode(2);
    TreeNode *pNodeB3 = CreateBinaryTreeNode(2);
    TreeNode *pNodeB4 = CreateBinaryTreeNode(3);
    TreeNode *pNodeB5 = CreateBinaryTreeNode(4);
    TreeNode *pNodeB6 = CreateBinaryTreeNode(4);
    TreeNode *pNodeB7 = CreateBinaryTreeNode(3);

ConnectTreeNodes(pNodeB1, pNodeB2, pNodeB3);
    ConnectTreeNodes(pNodeB2, pNodeB4, pNodeB5);
    ConnectTreeNodes(pNodeB3, pNodeB6, pNodeB7);

bool ans = isSymmetric(pNodeA1);

if (ans == true)
    {
        cout << "Symmetric Tree!" << endl;
    }
    else
    {
        cout << "Not Symmetric Tree!" << endl;
    }

bool ans1 = isSymmetric(pNodeB1);

if (ans1 == true)
    {
        cout << "Symmetric Tree!" << endl;
    }
    else
    {
        cout << "Not Symmetric Tree!" << endl;
    }
    DestroyTree(pNodeA1);
    DestroyTree(pNodeB1);
    return 0;
}

结果输出:
Not Symmetric Tree!
Symmetric Tree!

 
BinaryTree.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 
#ifndef _BINARY_TREE_H_
#define _BINARY_TREE_H_

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

TreeNode *CreateBinaryTreeNode(int value);
void ConnectTreeNodes(TreeNode *pParent,
                      TreeNode *pLeft, TreeNode *pRight);
void PrintTreeNode(TreeNode *pNode);
void PrintTree(TreeNode *pRoot);
void DestroyTree(TreeNode *pRoot);

#endif /*_BINARY_TREE_H_*/

BinaryTree.cpp:
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
 
#include <iostream>
#include <cstdio>
#include "BinaryTree.h"

using namespace std;

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

//创建结点
TreeNode *CreateBinaryTreeNode(int value)
{
    TreeNode *pNode = new TreeNode(value);

return pNode;
}

//连接结点
void ConnectTreeNodes(TreeNode *pParent, TreeNode *pLeft, TreeNode *pRight)
{
    if(pParent != NULL)
    {
        pParent->left = pLeft;
        pParent->right = pRight;
    }
}

//打印节点内容以及左右子结点内容
void PrintTreeNode(TreeNode *pNode)
{
    if(pNode != NULL)
    {
        printf("value of this node is: %d\n", pNode->val);

if(pNode->left != NULL)
            printf("value of its left child is: %d.\n", pNode->left->val);
        else
            printf("left child is null.\n");

if(pNode->right != NULL)
            printf("value of its right child is: %d.\n", pNode->right->val);
        else
            printf("right child is null.\n");
    }
    else
    {
        printf("this node is null.\n");
    }

printf("\n");
}

//前序遍历递归方法打印结点内容
void PrintTree(TreeNode *pRoot)
{
    PrintTreeNode(pRoot);

if(pRoot != NULL)
    {
        if(pRoot->left != NULL)
            PrintTree(pRoot->left);

if(pRoot->right != NULL)
            PrintTree(pRoot->right);
    }
}

void DestroyTree(TreeNode *pRoot)
{
    if(pRoot != NULL)
    {
        TreeNode *pLeft = pRoot->left;
        TreeNode *pRight = pRoot->right;

delete pRoot;
        pRoot = NULL;

DestroyTree(pLeft);
        DestroyTree(pRight);
    }
}

 
 
 
 
 
 
 
 
 
 
 
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
53
 
bool isSymmetric(TreeNode *root)
{

if(root == NULL)
    {
        return true;
    }
    queue<TreeNode *> lt, rt;
    if(root->left != NULL)
    {
        lt.push(root->left);
    }
    if(root->right != NULL)
    {
        rt.push(root->right);
    }
    TreeNode *l;
    TreeNode *r;
    while(!lt.empty() && !rt.empty())
    {
        l = lt.front();
        lt.pop();
        r = rt.front();
        rt.pop();

if(l == NULL && r == NULL)
        {
            continue;
        }
        if( (l != NULL && r == NULL) || (l == NULL && r != NULL) )
        {
            return false;
        }
        if(l->val != r->val)
        {
            return false;
        }
        /*这个入队列的顺序很重要*/
        lt.push(l->left);
        lt.push(l->right);
        rt.push(r->right);
        rt.push(r->left);
    }
    if(lt.empty() && rt.empty())
    {
        return true;
    }
    else
    {
        return false;
    }

}

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
bool isSameTree(TreeNode *p, TreeNode *q)
{

if(p == NULL)
    {
        return q == NULL;
    }
    else if(q == NULL)
    {
        return false;
    }
    else if(p->val == q->val)
    {
        return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    }
    else
    {
        return false;
    }
}

【遍历二叉树】09判断二叉树是否关于自己镜像对称【Symmetric Tree】的更多相关文章

  1. PAT-1119(Pre- and Post-order Traversals)+前序和后序遍历确定二叉树+判断二叉树是否唯一

    Pre- and Post-order Traversals PAT-1119 这题难度较大,主要需要考虑如何实现根据前序遍历和后序遍历来确定一颗二叉树 一篇好的文章: 题解 import java. ...

  2. 【剑指offer】判断二叉树是否为平衡二叉树

    2013-09-03 14:16:51 面试题39:求二叉树的深度.判断二叉树是否为平衡二叉树 小结: 根据平衡二叉树的定义,需要判断每个结点,因此,需要遍历二叉树的所有结点,并判断以当前结点为根的树 ...

  3. 判断二叉树是否BST

    一.问题: 请实现一个函数,检查一棵二叉树是否为二叉查找树.给定树的根结点指针TreeNode* root,请返回一个bool,代表该树是否为二叉查找树. 二.思路: 解法一:从根节点开始遍历二叉树, ...

  4. [Leetcode 100]判断二叉树相同 Same Tree

    [题目] 判断二叉树是否相同. [思路] check函数. p==null并且q==null,返回true;(两边完全匹配) p==null或q==null,返回false;(p.q其中一方更短) p ...

  5. 【easy】110. Balanced Binary Tree判断二叉树是否平衡

    判断二叉树是否平衡 a height-balanced binary tree is defined as a binary tree in which the depth of the two su ...

  6. 二叉树的遍历--C#程序举例二叉树的遍历

    二叉树的遍历--C#程序举例二叉树的遍历 关于二叉树的介绍笨男孩前面写过一篇博客 二叉树的简单介绍以及二叉树的存储结构 遍历方案 二叉树的遍历分为以下三种: 先序遍历:遍历顺序规则为[根左右] 中序遍 ...

  7. 剑指offer58:对称的二叉树。判断一颗二叉树是不是对称的,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的

    1 题目描述 请实现一个函数,用来判断一颗二叉树是不是对称的.注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的. 2 思路和方法 定义一种遍历算法,先遍历右子结点再遍历左子结点:如对称先序 ...

  8. 剑指offer系列32-----对称二叉树的判断

    [题目]请实现一个函数,用来判断一颗二叉树是不是对称的.注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的. package com.exe7.offer; /** * [题目]请实现一个函 ...

  9. C++版 - 剑指offer 面试题24:二叉搜索树BST的后序遍历序列(的判断) 题解

    剑指offer 面试题24:二叉搜索树的后序遍历序列(的判断) 题目:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果.如果是则返回true.否则返回false.假设输入的数组的任意两个 ...

随机推荐

  1. android中实现毛笔效果(View 中画图)

    近期有一个项目设计一个APP实现通过触摸屏实现毛笔写字效果.传统的绘画板程序直接通过Path的moveTo和LineTo便可实现简单的线条绘画程序.然而要达到毛笔的笔锋效果则须要更为具体点的设计.我的 ...

  2. ios __block typeof 编译错误解决

    type specifier missing a parameter list without types is only allowed in a function definition 解决: 工 ...

  3. python第三方库地址

    python第三方库的地址: requests: http://docs.python-requests.org/zh_CN/latest/user/quickstart.html beautifus ...

  4. Django模板系统(非常详细)(后台数据如何展示在前台)

    前面的章节我们看到如何在视图中返回HTML,但是HTML是硬编码在Python代码中的这会导致几个问题:1,显然,任何页面的改动会牵扯到Python代码的改动网站的设计改动会比Python代码改动更频 ...

  5. C#彻底解决Oledb连接Excel数据类型不统一的问题

    在使用Microsoft.Jet.OLEDB.4.0连接Excel,进行读取数据,相对使用传统的COM来读取数据,效率是很高的.但相对传统COM操作Excel来说,及存在数据类型转换的问题.因为使用O ...

  6. 【android】在Service的onStartCommand()中调用stopself()应该注意的问题

    在Service的onStartCommand()中调用stopself()后并不会立马destroy掉service,而是等onStartCommand()运行完才destroy. public c ...

  7. bug-2——tab中beforeActivate:在对象活动前触发

    $j("#tabs").tabs({ beforeActivate:function(event,ui){ var ret = apoCheck('${requestScope.a ...

  8. PHP数据库链接类(PDO+Access)实例分享

    这篇文章主要介绍了PHP数据库链接类(PDO+Access),有需要的朋友可以参考一下 PHP PDO Access链接 复制代码代码如下: class DbHelpClass     {       ...

  9. gulp 打包报错:ReferenceError: internalBinding is not defined

    > gulp build internal/util/inspect.js:31 const types = internalBinding('types'); ^ ReferenceError ...

  10. eclipse中,项目无法在tomcat中发布(project facet java version 1.7 is not supported)

    在tomcat中发布项目时无法添加项目,错误信息:project facet java version 1.7 is not supported,如下图 这是由于你的tomcat的jdk版本低于你项目 ...