Leetcode 101. Symmetric Tree

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

Input: 1 1
/ \ / \
2 3 2 3

[1,2,3], [1,2,3]

Output: true
Example 2:

Input: 1 1
/ \
2 2

[1,2], [1,null,2]

Output: false
Example 3:

Input: 1 1
/ \ / \
2 1 1 2

[1,2,1], [1,1,2]

Output: false

这道题目,我们借用一个isMirror函数,判断左右是否相等。
在isSymmetric中,我们判定root是空,则返回true,否则返回isMirror判定左右子树
isMirror中,我们判定两个都为空,那么遍历到了最底部,返回true,如果两个都不为空,并且值相等,那就递归一下,继续比较。
如果都不满足,则false

/**
 * 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* p, TreeNode* q) {
        if(p == NULL && q == NULL) return true;
        if(p != NULL && q != NULL && p->val == q->val)
            return isMirror(p->left, q->right) && isMirror(p->right, q->left); 
        return false;
    }
};

 

posted @ 2020-02-07 02:37  SteveYu  阅读(119)  评论(0编辑  收藏  举报