• 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;
        }
    };


  • 相关阅读:
    C Socket编程之Connect超时 (转)
    【c#】设置Socket连接、接收超时(转)
    socket测试远程地址能否连接并为连接设置超时(转)
    ZedGraph右键菜单怎样禁止它弹出(转)
    赚钱本身就是人生目的
    如果一个女人喜欢你,又不跟你在一起,而且只跟你很暧昧,那代表什么
    LayoutInflater的使用
    Android应用程序的生命周期
    Android的系统服务一览
    Android系统服务-简介
  • 原文地址:https://www.cnblogs.com/zclzqbx/p/4687101.html
Copyright © 2020-2023  润新知