[104]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
Note:
Bonus points if you could solve it both recursively and iteratively.
脑海中的我:按照中序左中右的顺序输出,然后另一个右中左的顺序输出,对比结果一样就皆大欢喜。然而,我好像想错了,比如上面第二棵树很明显就不行。
Solution1:(迭代)
 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 isSymmetric(TreeNode* root) {
13         queue<TreeNode*> st;
14         st.push(root);          
15         st.push(root); 
16         {     
17           while(!st.empty())
18           {
19             TreeNode* node1 = st.front();
20             st.pop();
21             TreeNode* node2 = st.front();
22             st.pop();
23             if(node1 == nullptr && node2 == nullptr) continue;
24             else if((node1 == nullptr || node2==nullptr) || node1->val != node2->val)
25             {
26               return false;
27             }
28             st.push(node1->left);
29             st.push(node2->right);               
30             st.push(node1->right);
31             st.push(node2->left);          
32           }
33         }
34       return true;
35     }
36 };

利用的树的层次遍历,往队列里面塞入树对称位置上的数,然后出队列时对比数字是否一致即可。

solution2:(递归)

 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 isSymmetric(TreeNode* root) {
13         if(root == nullptr) return true;
14         return isMirror(root->left,root->right);
15     }
16     bool isMirror(TreeNode* root1,TreeNode* root2)
17     {
18       if(root1 == nullptr && root2 == nullptr) return true;
19       if(root1 == nullptr || root2 == nullptr) return false;
20       return (root1->val == root2->val) && 
21         isMirror(root1->left,root2->right)&&
22         isMirror(root1->right,root2->left);
23       
24     }
25 };


猜你喜欢

转载自www.cnblogs.com/Swetchine/p/11241731.html