zoukankan      html  css  js  c++  java
  • leetCode(15):Symmetric Tree 分类: leetCode 2015-06-21 11:49 78人阅读 评论(0) 收藏

    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
    

    Note:

    Bonus points if you could solve it both recursively and iteratively.

    首先递归方法:

    bool isChildSymmectric(TreeNode* node1,TreeNode* node2)
    {
    	if(node1==NULL && node2==NULL)
    		return true;
    	if(node1==NULL || node2==NULL || node1->val!=node2->val)
    		return false;
    	return isChildSymmectric(node1->left,node2->right) && isChildSymmectric(node1->right,node2->left);
    }
    
    bool isSymmetric(TreeNode* root)
    {
    	if(root==NULL)
    		return true;	
    	return isChildSymmectric(root->left,root->right);
    }

    循环方法:把左右子树依次压入到容器中,并一层一层地判断,如果不平衡则立即返回;直至没有新的结点压入到容器中。

    /**
     * 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;
        	vector<TreeNode*> nodes;
        	nodes.push_back(root);
        	int nodesBegin=0;
        	int nodesEnd=nodes.size();	
        	
        	while(nodesBegin<nodesEnd)
        	{
        		int b=nodesBegin;
        		int e=nodes.size()-1;
        		while(b<e)
        		{
        			if(nodes[b]==NULL && nodes[e]==NULL)
        			{
        				b++;
        				e--;
        				continue;
        			}
        			if((nodes[b]==NULL && nodes[e]) || (nodes[b] && nodes[e]==NULL)
        				|| (nodes[b]->val!=nodes[e]->val))
        				return false;
        				
        			nodes.push_back(nodes[b]->left);
        			nodes.push_back(nodes[b]->right);
        			
        			b++;
        			e--;			
        		}
        		while(b<nodesEnd)
        		{
        			if(NULL==nodes[b])
        			{
        				b++;
        				continue;
        			}
        			nodes.push_back(nodes[b]->left);
        			nodes.push_back(nodes[b]->right);
        			b++;
        		}
        		nodesBegin=nodesEnd;
        		nodesEnd=nodes.size();
        	}
        	return true;
        }
    };


  • 相关阅读:
    容器的发展历程
    oracle数据库删除了表空间后连接数据库提示ORA-01033:ORACLE initialization or shutdown
    Oracle数据库忘记用户名和密码怎么办
    maven项目pom文件引入本地jar包并打包的配置
    Java 9 新特性,看这里就明白了
    springboot项目统一处理返回报文体
    在springboot中用实体类获取配置文件的属性值
    2017《面向对象程序设计》寒假作业二
    css 绝对定位元素居中显示
    js防抖
  • 原文地址:https://www.cnblogs.com/zclzqbx/p/4687101.html
Copyright © 2011-2022 走看看