[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.

判断二叉树是否是平衡树,比如有两个节点n1, n2,我们需要比较n1的左子节点的值和n2的右子节点的值是否相等,同时还要比较n1的右子节点的值和n2的左子结点的值是否相等,以此类推比较完所有的左右两个节点。我们可以用递归和迭代两种方法来实现,写法不同,但是算法核心都一样。

递归方法 (Recursive Solution):

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        if (!root) return true;
        return isSymmetric(root->left, root->right);
    }
    bool isSymmetric(TreeNode *left, TreeNode *right) {
        if (!left && !right) return true;
        if (left && !right || !left && right || left->val != right->val) return false;
        return isSymmetric(left->left, right->right) && isSymmetric(left->right, right->left);
    }
    
};

迭代方法 (Iterative Solution):

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        if (!root) return true;
        queue<TreeNode*> q1, q2;
        q1.push(root->left);
        q2.push(root->right);
        
        while (!q1.empty() && !q2.empty()) {
            TreeNode *node1 = q1.front();
            TreeNode *node2 = q2.front();
            q1.pop();
            q2.pop();
            if((node1 && !node2) || (!node1 && node2)) return false;
            if (node1) {
                if (node1->val != node2->val) return false;
                q1.push(node1->left);
                q1.push(node1->right);
                q2.push(node2->right);
                q2.push(node2->left);
            }
        }
        return true;
    }
};

本文转自博客园Grandyang的博客,原文链接:[LeetCode] Symmetric Tree 判断对称树

,如需转载请自行联系原博主。

相关文章
|
3月前
|
Go
golang力扣leetcode 675.为高尔夫比赛砍树
golang力扣leetcode 675.为高尔夫比赛砍树
29 0
|
3月前
|
Go
golang力扣leetcode 101.对称二叉树
golang力扣leetcode 101.对称二叉树
34 0
|
3月前
leetcode-SQL-608. 树节点
leetcode-SQL-608. 树节点
16 0
|
2天前
|
算法 DataX
二叉树(中)+Leetcode每日一题——“数据结构与算法”“剑指Offer55-I. 二叉树的深度”“100.相同的树”“965.单值二叉树”
二叉树(中)+Leetcode每日一题——“数据结构与算法”“剑指Offer55-I. 二叉树的深度”“100.相同的树”“965.单值二叉树”
Leetcode1038. 从二叉搜索树到更大和树(每日一题)
Leetcode1038. 从二叉搜索树到更大和树(每日一题)
|
2月前
LeetCode 树-简单题 4个典例
LeetCode 树-简单题 4个典例
15 0
LeetCode | 101. 对称二叉树
LeetCode | 101. 对称二叉树
|
3月前
|
算法
leetcode-675:为高尔夫比赛砍树 (最短路径算法bfs,dijkstra,A*)
leetcode-675:为高尔夫比赛砍树 (最短路径算法bfs,dijkstra,A*)
29 0
|
3月前
leetcode-652:寻找重复的子树
leetcode-652:寻找重复的子树
16 0
|
3月前
|
Go
golang力扣leetcode 310.最小高度树
golang力扣leetcode 310.最小高度树
18 0