leetcode 101: Symmetric Tree

来源:互联网 发布:微博发淘宝客链接 编辑:程序博客网 时间:2024/06/06 10:59

问题描述:

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]
1
/ \
2 2
/ \ / \
3 4 4 3

But the following is not:
[1,2,2,#,3,#,3]
1
/ \
2 2
\ \
3 3

思路:

碰到树,而且还是看起来挺复杂的问题,一条路走到黑想不通,那么基本上都需要用递归来解决。递归就要形成可迭代的问题,构造可迭代函数,原来的 isSymmetric 不符合迭代两个镜面的比较这种递归,所以很容易想到要另写一个函数,该函数需要能够递归地调用自己。

由于每步比较是否对称时,都需要比较每一层对应的两个节点是否如此,所以可以写一个函数是使用两个节点输入作比较的。

想清楚这些,剩下的就是注意各项出口的严密性了。

代码:

class Solution {public:    bool isSymmetric(TreeNode* root) {        if (root == NULL) return true;        return isMirror(root->left,root->right);    }    bool isMirror(TreeNode *left, TreeNode *right)    {        if (left == NULL && right == NULL)            return true;        else if (left != NULL && right != NULL)        {            if (left->val != right->val) return false;   // compare the mirror nodes pair            else                return (isMirror(left->left, right->right) && isMirror(left->right, right->left));   //form the mirror nodes pair        }        else            return false;    }};
0 0
原创粉丝点击