Leetcode 101. Symmetric Tree

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Symmetric Tree

2. Solution

  • Recursive
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* 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 == NULL) {
return true;
}
return isMirror(root->left, root->right);
}

bool isMirror(TreeNode* left, TreeNode* right) {
if(left == NULL && right == NULL) {
return true;
}
if(left == NULL || right == NULL) {
return false;
}
return left->val == right->val && isMirror(left->left, right->right) && isMirror(left->right, right->left);
}
};
  • Iterative
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    /**
    * 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 == NULL) {
    return true;
    }
    queue<TreeNode*> nodes;
    nodes.push(root);
    nodes.push(root);
    while(!nodes.empty()) {
    TreeNode* left = nodes.front();
    nodes.pop();
    TreeNode* right = nodes.front();
    nodes.pop();
    if(left == NULL && right == NULL) {
    continue;
    }
    if(left == NULL || right == NULL) {
    return false;
    }
    if(left->val == right->val) {
    nodes.push(left->left);
    nodes.push(right->right);
    nodes.push(left->right);
    nodes.push(right->left);
    }
    else {
    return false;
    }
    }
    return true;
    }
    };

Reference

  1. https://leetcode.com/problems/symmetric-tree/description/
如果有收获,可以请我喝杯咖啡!