【树】对称二叉树

题目:

解法:

方法一:递归的方法

 1 //小集合和大集合均OK
 2 public class Solution
 3 {
 4     public boolean isSymmetric(TreeNode root)
 5     {
 6         if (root == null)
 7         {
 8             return true;
 9         }
10         return helper(root.left, root.right);
11     }
12 
13     private boolean helper(TreeNode a, TreeNode b)
14     {
15         if (a == null && b == null)
16             return true;
17         if (a == null || b == null)
18             return false;
19         if (a.val != b.val)
20             return false;
21         return helper(a.left, b.right) && helper(a.right, b.left);
22     }
23 }

方法二:迭代的方法

 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     {
14         if (NULL == root)
15         {
16             return true;
17         }
18 
19         queue<TreeNode *> lf, rt;
20         lf.push(root->left);
21         rt.push(root->right);
22 
23         TreeNode *l;
24         TreeNode *r;
25 
26         while (!lf.empty() && !rt.empty())
27         {
28             l = lf.front();
29             r = rt.front();
30             lf.pop();
31             rt.pop();
32 
33             if (l == NULL && r == NULL)
34             {
35                 continue;
36             }
37 
38             if (l == NULL || r == NULL)
39             {
40                 return false;
41             }
42 
43             if (l->val != r->val)
44             {
45                 return false;
46             }
47 
48             lf.push(l->left);
49 
50             // notice
51             lf.push(l->right);
52             rt.push(r->right);
53 
54             rt.push(r->left);
55         }
56 
57         if (lf.empty() && rt.empty())
58         {
59             return true;
60         }
61         else
62         {
63             return false;
64         }
65     }
66 };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12817468.html