[LeetCode]--Symmetric Tree

题目  

 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.

中文题意:给定一棵二叉树,判断其是否关于中心轴线对称。

分析

     判断一棵二叉树是否为对称的,我们必须遍历此二叉树,此题选择深度优先遍历,即首先访问出发点v,并将其标记为已访问过;然后依次从v触发搜索v的每个邻接点w。若w未被访问,则以w为新的出发点继续进行深度优先遍历,直到所有与v相通路径上的节点都被访问过为止。
      此题中,我们通过对二叉树的左子树和右子树执行函数isMirrorTree,判断其是否为对称结构,注意,由于拆分成了两棵树,我们需要仔细选定函数的参数,根据题意,该操作应分别对应左子节点的左子树和右子节点的右子树,以及左子节点的右子树和右子节点的左子树。
      还应注意的是,不要忘记判断节点为空的情况。

解答

/**
 * 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;
    	if(root->left==NULL && root->right==NULL)
    		return true;
    	if(root->left==NULL || root->right==NULL)
    		return false;
        return isMirrorTree(root->left,root->right);
    }
    bool isMirrorTree(TreeNode *p, TreeNode *q){
    	if(p==NULL && q==NULL)
    		return true;
    	if(p==NULL || q==NULL)
    		return false;
    	if(p->val!=q->val)
    		return false;
    	if((p->left==NULL && p->right==NULL) && (q->left==NULL && q->right==NULL)){
    		if(p->val==q->val)
    			return true;
		}
		return (isMirrorTree(p->left,q->right) && (isMirrorTree(p->right,q->left)));
	}
};
   时间复杂度为O(n)。


猜你喜欢

转载自blog.csdn.net/weixin_38057349/article/details/78852855