Symmetric Tree

来源:互联网 发布:单片机键盘输入 编辑:程序博客网 时间:2024/05/17 23:40

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.

Subscribe to see which companies asked this question

题目:观察一棵树是不是对称的二叉树。

思想:利用递归依次判断,新写一个函数用来传递对称的结点即可,代码:

/**
 * 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) return true;
        return isSymmetric(root->left,root->right);
    }
    bool isSymmetric(TreeNode* leftCode,TreeNode* rightCode){
        if(!leftCode && !rightCode) return true;
        if(leftCode && !rightCode || 
            rightCode && !leftCode || 
            leftCode->val != rightCode->val) 
            return false;
        return isSymmetric(leftCode->left,rightCode->right) && isSymmetric(leftCode->right,rightCode->left);
    }
};

0 0