【LeetCode-面試演算法經典-Java實現】【100-Same Tree(兩棵樹是否相同)】,leetcode--java
【100-Same Tree(兩棵樹是否相同)】【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】原題
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.
題目大意
給定兩個二叉樹,判斷這兩棵樹是否相等。
僅當兩棵樹的結構相同,結點值都相等時都會相等。
解題思路
使用遞迴進行求解,先判斷當前結點值是否相等,如果相等就再比較其左右子樹,只有當所有的結點都相等才相等。
代碼實現
樹結點類
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; } if (p == null && q != null) { return false; } return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right); }}
評測結果
點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。
特別說明歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47333329】
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。