欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode——Same Tree(判断两棵树是否相同)

发布时间:2025/3/19 编程问答 38 豆豆
生活随笔 收集整理的这篇文章主要介绍了 LeetCode——Same Tree(判断两棵树是否相同) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
问题:

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.

 

分析:

考虑使用深度优先遍历的方法,同时遍历两棵树,遇到不等的就返回。

代码如下:

/*** Definition for binary tree* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ public class Solution {public boolean isSameTree(TreeNode p, TreeNode q) {if(p == null || q==null){return p==q;}if(p.val != q.val){return false;}return isSameTree(p.left,q.left)&& isSameTree(p.right,q.right);} }

转载于:https://www.cnblogs.com/chrischennx/p/4009412.html

总结

以上是生活随笔为你收集整理的LeetCode——Same Tree(判断两棵树是否相同)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。