Symmetric Tree(对称树)

来源:互联网 发布:稳稳ip软件免费版 编辑:程序博客网 时间:2024/05/19 18:13

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.

1.个人分析
(1)二叉树是否对称可以理解为,将二叉树反转后与原二叉树相同就是对称的。可以很容易地想到递归方法,将根节点的左右子节点进行对调,然后递归处理其他节点,最后比较反转后的二叉树与原二叉树是否相同。
(2)思路一需要新创建一个输入二叉树的副本,因此会增加空间复杂度,有没有一种只在原二叉树基础上就能判断是否对称的方法?其实只需将左子树或右子树的一个进行反转,最后判断左右子树是否相同。

2.个人解法
(1)递归解法(复杂版)

TreeNode* invertTree(TreeNode* root){       if(root == NULL)           return NULL;    if(root->left || root->right)        swap(root->left, root->right);    invertTree(root->left);    invertTree(root->right);    return root;}bool isSameTree(TreeNode* p, TreeNode* q){    if(!p && !q)        return true;    else if(!p || !q || p->val != q->val)        return false;    return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);}bool isSymmetric(TreeNode* root){    if(!root)        return true;    TreeNode *leftSub = invertTree(root->left);    return isSameTree2(leftSub, root->right);}

(2)递归解法(精简版)

bool isMirror(TreeNode *p, TreeNode *q){    if(!p && !q)        return true;    else if(!p || !q || p->val != q->val)        return false;    return isMirror(p->left, q->right) && isMirror(p->right, q->left);}bool isSymmetric(TreeNode* root){    if(!root) return true;    return isMirror(root->left, root->right);}

3.参考解法
循环迭代法:

bool ismirror(TreeNode *p, TreeNode *q){    if(!p&&!q) return true;    else if(!p||!q) return false;    if(p->val!=q->val) return false;    else return true;}bool isSymmetric(TreeNode* root){    if(!root) return true;    queue<TreeNode*> l,r;    l.push(root->left);    r.push(root->right);    while(!l.empty() && !r.empty()){        TreeNode *p=l.front(), *q=r.front();        l.pop();        r.pop();        if(!p&&!q) continue;        if(!ismirror(p,q)) return false;        l.push(p->left);        r.push(q->right);        l.push(p->right);        r.push(q->left);    }    return true;}

4.总结
到目前为止仍然没有对树或者二叉树的结构有个完整的把握,因为自己一开始就要去创建一个新的二叉树副本并将其反转,也许是受到之前的经验所导致的,后面又是在查阅相关资料的过程中才突然意识到只需去比较根节点的左右子树即可(每次没思路的时候查阅其他资料时总能冒出解法,自己都感到神奇)。

PS:

  • 题目的中文翻译是本人所作,如有偏差敬请指正。
  • 其中的“个人分析”和“个人解法”均是本人最初的想法和做法,不一定是对的,只是作为一个对照和记录。
0 0