欢迎访问 生活随笔!

生活随笔

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

编程问答

leetcode 100.Same Tree

发布时间:2025/3/15 编程问答 32 豆豆
生活随笔 收集整理的这篇文章主要介绍了 leetcode 100.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.

解决方案:Runtime: 191 ms

public class Solution {public boolean isSameTree(TreeNode p, TreeNode q) {if(p==null&&q==null)return true;if(p!=null&&q==null || p==null&&q!=null){//here can be if(p == null || q == null){,but it will take more timereturn false;}if(p.val == q.val){return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);}return false;} }

 

总结:这道题目注意几个判断就好了,其他的就是单纯的递归。

转载于:https://www.cnblogs.com/Pillar/p/4309031.html

总结

以上是生活随笔为你收集整理的leetcode 100.Same Tree的全部内容,希望文章能够帮你解决所遇到的问题。

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