文巾解题 100. 相同的树
生活随笔
收集整理的這篇文章主要介紹了
文巾解题 100. 相同的树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 題目描述
?
?2 解題思路
2.1 DFS
class Solution:def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:if(p==None and q==None):return Trueelif(p==None or q==None):return Falsedef dfs(p_,q_):if(p_==None and q_==None):return Trueelif(p_==None or q_==None):return Falseelif(p_.val !=q_.val):return False #判斷此時的q和p 根節點是否相等else:return dfs(p_.left,q_.left) and dfs(p_.right,q_.right) #遞歸判斷p和q的左和右子樹 return(dfs(p,q))?2.2 BFS
class Solution:def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:if(p==None and q==None):return Trueelif(p==None or q==None):return Falsep_=[p]q_=[q]while(p_ and q_):tmp_p=p_.pop(0)tmp_q=q_.pop(0)if(tmp_p==None and tmp_q==None):continueelif(tmp_p==None or tmp_q==None):return Falseelif(tmp_p.val!=tmp_q.val):return False #判斷當前p和q的根節點是否相同else:p_.append(tmp_p.left)q_.append(tmp_q.left)p_.append(tmp_p.right)q_.append(tmp_q.right) #將p和q的左右子節點入棧return True總結
以上是生活随笔為你收集整理的文巾解题 100. 相同的树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 文巾解题 326. 3的幂
- 下一篇: 文巾解题 45. 跳跃游戏 II