# 【LeetCode】Symmetric Tree(对称二叉树)

## 题目如下：

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


    1
/ \
2   2
\   \
3   3


## 代码如下：

 1 /**
2  * Definition for a binary tree node.
3  * struct TreeNode {
4  *     int val;
5  *     TreeNode *left;
6  *     TreeNode *right;
7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8  * };
9  */
10 class Solution {
11 public:
12     vector<int> LPreOrder(TreeNode* tree){//LDR中序遍历
13         stack<TreeNode*>st;//节点堆栈
14         vector<int>res;
15         TreeNode* pt;
16         if(tree==NULL)return res;
17         pt=tree;
18         while(pt!=NULL||st.size()!=0){
19             while(pt!=NULL){//先访问左节点
20                 st.push(pt);
21                 pt=pt->left;
22             }
23             pt=st.top();//最下边的左节点
24             res.push_back(pt->val);//保存数值
25             st.pop();
26             pt=pt->right;//访问右节点
27         }
28         return res;
29     }
30     vector<int> RPreOrder(TreeNode* tree){//RDL中序遍历
31         stack<TreeNode*>st;
32         vector<int>res;
33         TreeNode* pt;
34         if(tree==NULL)return res;
35         pt=tree;
36         while(pt!=NULL||st.size()!=0){
37             while(pt!=NULL){
38                 st.push(pt);
39                 pt=pt->right;
40             }
41             pt=st.top();
42             res.push_back(pt->val);
43             st.pop();
44             pt=pt->left;
45         }
46         return res;
47     }
48     bool isSymmetric(TreeNode* root) {
49         if(root==NULL)//根节点是否为空
50             return true;
51         if(root->left==NULL||root->right==NULL){//左右子树其中一个是否为空
52             if(root->left==NULL&&root->right==NULL)//左右子树是否为空
53                 return true;
54             return false;
55         }
56         else{
57             if(root->left->val!=root->right->val)return false;
58             vector<int>Lorder,Rorder;
59             Lorder=LPreOrder(root->left);//遍历
60             Rorder=RPreOrder(root->right);//遍历
61             if(Lorder!=Rorder)return false;//判断遍历结果是否相同
62             return true;
63         }
64     }
65 };

 1 /**
2  * Definition for a binary tree node.
3  * struct TreeNode {
4  *     int val;
5  *     TreeNode *left;
6  *     TreeNode *right;
7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8  * };
9  */
10 class Solution {
11 public:
12     bool isMirror(TreeNode* t1,TreeNode* t2){
13         if(t1==NULL&&t2==NULL)return true;
14         if(t1==NULL||t2==NULL)return false;
15         return (t1->val==t2->val)
16             &&isMirror(t1->left,t2->right)
17             &&isMirror(t2->left,t1->right);
18     }
19     bool isSymmetric(TreeNode* root) {
20         return isMirror(root,root);
21     }
22 };

posted @ 2018-11-24 14:06  1000sakura  阅读(111)  评论(0编辑  收藏