[leetCode] Symmetric Tree

本文介绍了一种检查二叉树是否为中心对称的方法,提供了两种实现方式:递归和迭代。递归方法通过比较左右子树来判断对称性,而迭代方法则采用层次遍历的方式进行检查。

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

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

 

But the following is not:

    1
   / \
  2   2
   \   \
   3    3

 

Note:
Bonus points if you could solve it both recursively and iteratively.

 

思路一:递归思想。时间复杂度O(n),空间复杂度O(logN)

  

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

思路二:迭代。层次遍历的思想。时间复杂度O(n),空间复杂度O(logN)

  

 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         queue<TreeNode *> q;
15         q.push(root->left);
16         q.push(root->right);
17         
18         while (!q.empty()) {
19             TreeNode *p1 = q.front();
20             q.pop();
21             TreeNode *p2 = q.front();
22             q.pop();
23             
24             if (!p1 && !p2) continue;
25             if (!p1 || !p2) return false;
26             if (p1->val != p2->val) return false;
27             
28             q.push(p1->left);
29             q.push(p2->right);
30             
31             q.push(p1->right);
32             q.push(p2->left);
33         }
34         
35         return true;
36     }
37  
38 };

 

转载于:https://www.cnblogs.com/vincently/p/4232530.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值