leetcode刷题之旅(100)Same Tree

题目描述

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

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


样例

Example 1:

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

Example 2:

Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

Example 3:

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false

思路分析

先序遍历,依次比较节点值即可

二叉树类的题,要注意递归方法的使用


循环写法:层序遍历 利用队列,依次比较两树中每个节点值


代码

方法一:递归

public boolean isSameTree(TreeNode p, TreeNode q) {
		 if (p==null && q==null) {  //都为空 即相等
			return true;
		}
		 if (p==null || q==null) {  //任一为空 不满足条件 终止遍历
			return false;
		}
		 if (p.val == q.val) {  //节点值对应相等 则比较左右子树的值
			 return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);  //递归实现遍历整个二叉树
		}
		 return false;
	 }

结果



方法二:循环写法

public boolean isSameTree(TreeNode p, TreeNode q) {
		 Queue<TreeNode> queue = new LinkedList<TreeNode>();
		 queue.offer(p);
		 queue.offer(q);
		 while ( !queue.isEmpty() ){
			 TreeNode temp1 = queue.poll();
			 TreeNode temp2 = queue.poll();
			 if (temp1==null && temp2==null) {
				continue;
			}
			 if (temp1==null || temp2==null || temp1.val != temp2.val) {
				return false;
			}
			 queue.offer(temp1.left);
			 queue.offer(temp2.left);
			 queue.offer(temp1.right);
			 queue.offer(temp2.right);
		 }
		return true;
	 }


结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值