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


  • 相关阅读:
    pytest
    pytest 跳过测试用例 skip
    pytest
    pytest -allure标记用例级别severity
    pytest-
    pytest-分布式执行(pytest-xdist)
    4、win10搭建easy-mock平台
    pandas日期缺失,空值填充方法
    Pandas拼接操作(concat,merge,join和append)的区别
    关于docker容器和镜像的区别
  • 原文地址:https://www.cnblogs.com/zclzqbx/p/4687101.html
Copyright © 2011-2022 走看看