LeetCode——Same Tree(判断两棵树是否相同)
生活随笔
收集整理的這篇文章主要介紹了
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(判断两棵树是否相同)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2014 ACM/ICPC 鞍山赛区网络
- 下一篇: C++学习之路: 单例模板