The Solution to Leetcode 101 Symmetric Tree

来源:互联网 发布:大闹天宫数据库密码 编辑:程序博客网 时间:2024/06/06 05:02

Question:

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
思路:

判断一个二叉树是不是对称二叉树。

1.左右节点为空,是。

2.左节点为空,右节点非空,不是。

3.左节点非空,右节点为空,不是。

4.左右节点都非空,但值不相等,不是。

用递归的方法继续判断。

Answer:

/** * 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;        else        return testSymmetric(root->left,root->right);    }    bool testSymmetric(TreeNode* left, TreeNode* right) {         //1.左右节点都为空        if(left==NULL&&right==NULL)              return true;          //左节点为空,右节点非空        else if(left==NULL&&right!=NULL)              return false;          //左节点非空,右节点为空        else if(left!=NULL&&right==NULL)              return false;          //左右节点都非空,但值不相等        else if(left!=NULL&&right!=NULL&&left->val!=right->val)              return false;           else               return testSymmetric(left->left,right->right)&&testSymmetric(left->right,right->left);      } };

Run code result:

Your input
[1,2,2,3,4,4,3]
Your answer
true
Expected answer
true



原创粉丝点击