Symmetric Tree

来源:互联网 发布:php接口的用途 编辑:程序博客网 时间:2024/06/03 12:48
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

思路:题目要求判断一个树其本身是不是对称的。

(1)当这个树为NULL的时候,其本身即为对称,返回true

(2)当这个树不为NULL的时候,如果其左右子树均为NULL,显然也是对称的,返回true

(3)当左右子树有一个为NULL,一个不为NULL的时候,这个树是不对称的,返回false

(4)当左右子树的节点值相等的时候,且左子树的右节点和右子树的左节点是对称,且左子树的左节点和右子树的右节点是对称的时候,整个树是对称的

代码如下所示:

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


0 0