LeetCode:Same Tree - 判斷兩顆樹是否相等

一、題目名稱java

Same Tree(判斷兩棵樹是否相等)node

二、題目地址ide

https://leetcode.com/problems/same-tree/函數

三、題目內容code

英文: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.遞歸

中文:給定兩顆二叉樹,寫一個函數判斷這兩棵樹是否相等。若是兩棵樹的結構和各節點中保存的值是相等的,則認爲這兩棵樹相等。leetcode

四、解題方法開發

本題能夠採用先根遍歷的方法,從上到下遞歸考察各節點。在任意一對節點的比較中,若是左右枝是否爲空的屬性和節點中的val值不相等,則認爲兩棵樹不是同一棵樹,不然繼續考察。若是遍歷結束後仍然不能證實這兩棵樹不是同一棵樹,則這兩棵樹就是相等的get

解決問題的Java代碼以下:it

/**
 * 功能說明:LeetCode 100 - Same Tree
 * 開發人員:Tsybius2014
 * 開發時間:2015年8月12日
 */
public class Solution {
    
    /**
     * 判斷兩個樹是否爲相等
     * @param p 樹p
     * @param q 樹q
     * @return
     */
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        } else if (
            (p == null && q != null) || 
            (p != null && q == null) || 
            p.val != q.val || 
            !isSameTree(p.left, q.left) || 
            !isSameTree(p.right, q.right)) {
            return false;
        } else {
            return true;
        }
    }
}

END

相關文章
相關標籤/搜索