题目
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
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.
题目的意思是给两个二叉树,判断两个二叉树是否相等,这里的相等要求结构和对应位置数值都相等,具体案例可以看一下原题。
思路
我们要确定一棵二叉树,根据树的基本理论,有三种解决办法方法:前序、中序、后序。
我这里使用了第一种方法——前序的方法。
首先进行结构上的判断,如果结构都不相同,两棵树必定不相同。结构上有三种情况:
- 跳出条件:两个节点都为空,返回真;
- 继续判定情况:两个节点都有值,需要进行进行数值的判定;
- 直接否定情况:一个为空,另一个不为空,直接返回假。
如果第二点成立,进行前序遍历,先判断该结点数值是否相同,不相等直接返回假,相等的话接着分别遍历左右子树。这里我利用了与(&&)的性质,&&的判定有先后顺序,如果&&的第一个判定为假,第二个判定就不会执行。因此,实现了先左后右的查询。
实现
Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
//首先进行结构判定
if(p == null && q == null){//两个结点都为空
return true;
} else if(p != null && q != null){//两个结点都有值
boolean result = true;//前序遍历 if(p.val != q.val){ result = false; } else { result = isSameTree(p.left, q.left) && isSameTree(p.right, q.right); } return result; } else {//一个结点有值,另一个没有 return false; }
}
}
任务七(letecode)
猜你喜欢
转载自blog.csdn.net/weixin_41741008/article/details/89061032
今日推荐
周排行