1. 程式人生 > >[LeetCode] Symmetric Tree

[LeetCode] Symmetric Tree

des lock 對稱 log and {} 對稱樹 script public

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.

判斷一棵樹的對稱性,利用遞歸按照對稱樹的性質判斷即可。

/**
 * Definition for a binary tree node.
 * 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 == nullptr)
            
return true; return isSymmetricCore(root->left, root->right); } bool isSymmetricCore(TreeNode* s, TreeNode* t) { if (s == nullptr && t == nullptr) return true; if (s == nullptr || t == nullptr) return false; if (s->val != t->val)
return false; return isSymmetricCore(s->left, t->right) && isSymmetricCore(s->right, t->left); } }; // 3 ms

用叠代來表述算法,利用兩個queue維護一棵樹根節點的左右兩棵子樹節點。然後判斷相對應的節點

/**
 * Definition for a binary tree node.
 * 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 == nullptr)
            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 == nullptr && node2 != nullptr) || (node1 != nullptr && node2 == nullptr))
                return false;
            if (node1 != nullptr && node2 != nullptr) {
                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;
    }
};
// 3 ms

[LeetCode] Symmetric Tree