zoukankan      html  css  js  c++  java
  • 101. Symmetric Tree

    欢迎fork and star:Nowcoder-Repository-github

    101. 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. 
    
    

    解析

    • 递归和迭代实现
    // 101. Symmetric Tree
    class Solution_101 {
    public:
    
    	// 递归调用,同时判断左子树的左节点与右子树的右节点,以及左子树的右节点与右子树的左节点。一旦这两个节点不相等,就返回false。 
    	bool isSymmetricHelp(TreeNode *left, TreeNode* right)
    	{
    		if (!left&&!right)
    		{
    			return true;
    		}
    		if (!left&&right ||left&&!right)
    		{
    			return false;
    		}
    		if (left->val!=right->val)
    		{
    			return false;
    		}
    
    		return isSymmetricHelp(left->left, right->right) && isSymmetricHelp(left->right, right->left);
    	}
    
    	bool isSymmetric(TreeNode *root) {
    
    		if (!root)
    		{
    			return true;
    		}
    		return isSymmetricHelp(root->left, root->right);
    	}
    
    	//非递归实现
    	//需要:对每一层成对送入队列,出队列比较
    	bool isSymmetric1(TreeNode* root) {
    		if (!root)
    		{
    			return true;
    		}
    		queue<TreeNode*> que;
    
    		que.push(root->left);
    		que.push(root->right);
    
    		while (!que.empty())
    		{
    			int size = que.size();
    			while (size)
    			{
    				TreeNode* left = que.front();
    				que.pop();
    				TreeNode* right = que.front(); //取出成对的元素
    				que.pop();
    				size -= 2;
    				if (!left&&!right)
    				{
    					continue;
    				}
    				if (!left&&right)
    				{
    					return false;
    				}
    				if (left&&!right)
    				{
    					return false;
    				}
    
    				if (left->val!=right->val)
    				{
    					return false;
    				}
    				que.push(left->left);
    				que.push(right->right);
    				que.push(left->right);
    				que.push(right->left);
    			}
    		}
    		return true;
    	}
    };
    

    101. Symmetric Tree

  • 相关阅读:
    地区表设计(包括数据插入) Dear
    本博客的内容
    linux msn
    相关的一些技术
    相关的一些产品
    考第一名的学生的发言
    AIX&LINUX操作系统调优
    shell for循环
    自动化测试
    DB2数据库日志
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8274528.html
Copyright © 2011-2022 走看看