101. 对称二叉树

 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 {
12 public:
13     bool isSymmetric(TreeNode* root) 
14     {
15         if(root == NULL || root->left == NULL && root->right == NULL) return true;
16         return symmetric(root,root);
17     }
18 
19     //1、两个根节点的值要相等
20     //2、左边的左子树和右边的右子树对称
21     //3、左边的右子树和右边的左子树对称
22     bool symmetric(TreeNode* root1,TreeNode* root2)
23     {
24         if(root1 == NULL && root2 == NULL) return true;
25         if(root1 == NULL || root2 == NULL) return false;
26         if(root1->val == root2->val) return symmetric(root1->left,root2->right) && symmetric(root1->right,root2->left);
27         else return false;
28     }
29 };

 

 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 //1、左根右遍历
11 //2、右根左遍历
12 class Solution 
13 {
14 public:
15     bool isSymmetric(TreeNode* root) 
16     {
17         if(root == NULL) return true;
18         stack<TreeNode*> s1,s2;
19         auto head1 = root->left,head2 = root->right;
20         //为什么第二个||不是取&&,因为[1,0]
21         while(!s1.empty() || head1 != NULL || !s2.empty() || head2 != NULL)
22         {
23             if(head1 != NULL && head2 != NULL) 
24             {
25                 s1.push(head1),head1 = head1->left;
26                 s2.push(head2),head2 = head2->right;
27             }
28             else if(head1 == NULL && head2 == NULL) 
29             {
30                 head1 = s1.top(),s1.pop();
31                 int a = head1->val;
32                 head1 = head1->right;
33 
34                 head2 = s2.top(),s2.pop();
35                 int b = head2->val;
36                 head2 = head2->left;
37                 if(a != b) return false;
38             }
39             else return false;
40         }
41         return true;
42     }
43 };

 

posted @ 2020-03-24 11:24  Jinxiaobo0509  阅读(152)  评论(0)    收藏  举报