Symmetric Tree @leetcode

!本题分为迭代版和递归版,递归版比较直接,按照树遍历即可。跌代版这里创建了两个队列,每遇到一对节点(初始为根节点的左右子):

1.先对比这两个节点的值是否相等:不相等则结束循环,相等则进入2

2.把它们的左右子节点,交叉安插到自己的队列中,然后对队列里的front,作为一对节点,走1

!iterative

 1 if(!root) return true;
 2         queue<TreeNode*> queueStep;
 3         queue<TreeNode*> queueStep2;
 4         TreeNode *tn1,*tn2;
 5         tn1 = root->left;
 6         tn2 = root->right;
 7         while(1){
 8             if(!tn1 && tn2) return false;
 9             if(!tn2 && tn1) return false;
10             if(tn1 && tn2 && tn1->val != tn2->val) return false;
11             
12             if(tn1){
13                 queueStep.push(tn1->left);
14                 queueStep.push(tn1->right);
15             }
16             if(tn2){
17                 queueStep2.push(tn2->right);
18                 queueStep2.push(tn2->left);
19             }
20             if(queueStep.size() == 0 && queueStep2.size() == 0) return true;
21             /*else if(queueStep.size() == 0) return false;
22             else if(queueStep2.size() == 0) return false;*/
23 
24             tn1 = queueStep.front();
25             queueStep.pop();
26 
27             tn2 = queueStep2.front();
28             queueStep2.pop();
29         }

!recursive

 1 /**
 2  * Definition for binary tree
 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 == NULL) return true;
14         return isSymmetricSmall(root->left,root->right);
15     }
16 
17     bool isSymmetricSmall(TreeNode *left,TreeNode *right){
18         if(left == NULL && right == NULL) return true;
19         else if(left == NULL) return false;
20         else if(right == NULL) return false;
21 
22         if(left->val != right->val) return false;
23         
24         if(isSymmetricSmall(left->right,right->left) && isSymmetricSmall(left->left,right->right))
25             return true;
26         else
27             return false;
28     }
29 };

 

posted @ 2013-12-01 13:16  沙茶面  阅读(161)  评论(0编辑  收藏  举报