[LeetCode] 101. Symmetric Tree

题目链接:传送门

Description

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.

Solution

题意:

判断一棵二叉树是否对称

思路:

递归处理

/**
 * 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 isTreesSymmetric(TreeNode* root1, TreeNode* root2) {
        if (!root1 && !root2)  return true;
        if (root1 && root2 && root1->val == root2->val) {
            return isTreesSymmetric(root1->left, root2->right)
                && isTreesSymmetric(root1->right, root2->left);
        }
        return false;
    }
    bool isSymmetric(TreeNode* root) {
        return !root || isTreesSymmetric(root->left, root->right);
    }
};
posted @ 2018-02-26 00:51  酒晓语令  阅读(101)  评论(0编辑  收藏  举报