LeetCode Same Tree

本文介绍了一种使用层次遍历方法判断两棵二叉树是否等价的算法实现,重点在于采用LinkedList作为队列存储节点,通过比较节点值及结构来确保两棵树完全相同。

题目:

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

题意:

就是用一个函数来判断两棵二叉树是否在结构,节点的数值上是否相同。

此题是树的典型应用,但是因为LZ之前在数据结构这一块上花的时间比较少,所以最近在做这样的一道题都要花很多时间,但是却很有收获的,因为可以补一补自己在数据结构这一块的缺陷。

这道题首先有两种典型的做法,分别是递归和非递归。那么LZ比较傻傻地采用非递归的方法来实现,就是考虑用层次遍历的方法来实现,而且层次遍历是采用LinkedList来实现。也就是队列来实现。这个必须要记住,在java里是用LinkedList来模拟。有先进先出的特点嘛。判断的依据就是看当前节点是否为空,并且它的数据是否相同。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution 
{
    public static boolean isSameTree(TreeNode p,TreeNode q)
	{
		LinkedList<TreeNode> node1 = new LinkedList<TreeNode>();
		//Stack<TreeNode> node1 = new Stack<TreeNode>();
		
		LinkedList<TreeNode> node2 = new LinkedList<TreeNode>();
		//Stack<TreeNode> node2 = new Stack<TreeNode>();

		if(p == null && q == null)
			return true;
		else if((p == null && q != null) ||(p != null && q == null))
			return false;
		else if(p != null && q != null)
		{
			node1.push(p);
			node2.push(q);
			while(!node1.isEmpty() && !node2.isEmpty())
			{
				TreeNode curr1 = (TreeNode) node1.peek();
				//System.out.println(curr1.val);
				node1.poll();
				TreeNode curr2 = (TreeNode) node2.peek();
				//System.out.println(curr2.val);
				node2.poll();
				/*if(!isSameNode(curr1.left,curr1.left))
					return false;*/
				if((curr1.left == null && curr2.left != null) || (curr1.left != null && curr2.left == null) || (curr1.val != curr2.val))
					return false;
				if(curr1.left != null  && curr2.left != null)
				{
					node1.push(curr1.left);
					node2.push(curr2.left);
				}
				/*if(!isSameNode(curr1.right,curr2.right))
					return false;*/
				if((curr1.right == null && curr2.right != null) || (curr1.right != null && curr2.right == null) || (curr1.val != curr2.val))
					return false;
				if(curr1.right != null || curr2.right != null)
				{
					node1.push(curr1.right);
					node2.push(curr2.right);
				}
			}
		}
		return true;
	}
}

可以看在代码中,首先单独处理root节点,分别分三种情况来处理,都为空,那么返回true;一个为空,另一个不为空,那么返回false;两个都不为空,也就是最复杂的情况,需要考虑用层次遍历来做。首先我用两个LinkedList来存储两棵二叉树的节点。每一次都用peek方法来将队列的头节点取出来,然后这里要注意的是,取出的头节点必须先比较其左子树节点或者是右子树节点,然后才能用push存入相应的队列中。因为考虑到某一个节点是空,如果没有先判断是否为空,或者其节点值是否相同,而盲目地进行插入,会出现空指针错误;而且先判断又有一个好处,就是一旦发现两个节点的左子树或者是右子树节点不一致,那么可以立即就返回false,那么后面的push就不用做了,省去了很多麻烦。然后在整个循环的外面再return true;这样就会使得这个方法完整了。当然我在想,这道题目也是可以用Stack来做,虽然说栈是先进后出,但是不影响这道题对两棵树的判断,因为反正我每一个节点都需要遍历,而且因为不是真正意义上求层次遍历,所以不用非常按照固定的路径来求,故用Stack来做也是可以的。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值