Leet Code OJ 100. Same Tree [Difficulty: Easy]
生活随笔
收集整理的這篇文章主要介紹了
Leet Code OJ 100. Same Tree [Difficulty: Easy]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
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.
翻譯:
給2個二叉樹,寫一個程序去檢驗它們是否“相同”。
如果2個二叉樹的結構相同,并且它們的節點有相同的值,則被認為是“相同”的。
分析:
我的做法是遞歸判斷這兩棵樹的左右子樹,然后判斷它們的值是否相等。
代碼:
/*** Definition for a binary tree node.* 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 true;}if(p==null||q==null){return false;}boolean left=isSameTree(p.left,q.left);boolean right=isSameTree(p.right,q.right);boolean val=(p.val==q.val);if(left&&right&&val){return true;}else{return false;}} }總結
以上是生活随笔為你收集整理的Leet Code OJ 100. Same Tree [Difficulty: Easy]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 263. Ug
- 下一篇: Leet Code OJ 70. Cli