数据结构与算法28

Leecode101

题目

给定一个二叉树,检查它是否是镜像对称的。

分析

这道题描述简单易懂,就是给一个树判断这个树是否左右对称。对此我觉得可以用二进制,左子树用0表示,右子树用1表示位置然后可以使树中每个结点都表示出来。如此镜像位置的两个结点用0-1表示出来会是互相取反。由此可以使取反的两个结点互相比较。

解法

根据分析来实现。

public class Solution 
{    
	public int MaxDepth(TreeNode root)         
	{               
		if(root == null)                
		{                        
			return 0;                
		}                
		else                
		{                        
			int ldepth = MaxDepth(root.left);                        
			int rdepth = MaxDepth(root.right);                        
			return Math.Max(ldepth,rdepth)+1;                
		}        
	}    
	public bool IsSymmetric(TreeNode root)     
	{        
		int deep = MaxDepth(root);        
		for(int i=1;i<deep;i++)        
		{            
		for(int j=0;j<(Math.Pow(2,i)/2);j++)            
		{                
			TreeNode test1 = root;                
			TreeNode test2 = root;                
			for(int k=0;k<i;k++)                
			{                    
				if(((1<<(i-k-1))&j)!=0)                    
				{                        
					if(test1!=null)                   
					{                            
						test1 = test1.right;                        
					}                        
					if(test2!=null)                        
					{                            
						test2 = test2.left;
                        
                    			}                    
                    		}                    
                    		else                    
                    		{                        
                    			if(test1!=null)                        
                    			{                            
                    				test1 = test1.left;                        
                    			}                        
                    			if(test2!=null)                        
                    			{                            
                    				test2 = test2.right;                        
                    			}                    
                    		}                
                    	}                
                    	if(test1==null&&test2==null)                
                    	{}                
                    	else if(test1==null||test2==null)                
                    	{                    
                    		return false;                
                    	}                
                    	else if(test1.val!=test2.val)                
                    	{                    
                    	return false;                
                    	}            
                    }        
                    }        
                    return true;       
	}
}

效果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值