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.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


思路:

两个指针指向根节点,一个做中序遍历,一个做逆中序遍历,比较每个节点的值。

代码:

递归实现:
/**
 * 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) {
        return compare(root, root);
    }
    
    bool compare(TreeNode * node1, TreeNode * node2){
        if(node1 == NULL && node2 == NULL){
            return true;
        }
        else if(node1 != NULL && node2 != NULL && node1->val == node2->val){
            return compare(node1->left, node2->right) && compare(node1->right, node2->left);
        }
        else{
            return false;
        }
    }
};

非递归实现:
/**
 * 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) {
        queue<TreeNode*> order1;
        queue<TreeNode*> order2;
        
        if(root == NULL){
            return true;
        }
        
        order1.push(root);
        order2.push(root);
        while(!order1.empty() && !order2.empty()){
            TreeNode* node1 = order1.front();
            order1.pop();
            TreeNode* node2 = order2.front();
            order2.pop();
            
            if(node1->left != NULL && node2->right != NULL && node1->left->val == node2->right->val){
                order1.push(node1->left);
                order2.push(node2->right);
            }
            else if(!(node1->left == NULL && node2->right == NULL))
            {
                return false;
            }
            if(node1->right != NULL && node2->left != NULL && node1->right->val == node2->left->val){
                order1.push(node1->right);
                order2.push(node2->left);
            }
            else if(!(node1->right == NULL && node2->left == NULL))
            {
                return false;
            }
        }
    }
};


你可能感兴趣的:(LeetCode,算法)