【LeetCode】100. Same Tree 解題報告(Java & Python)

做者: 負雪明燭
id: fuxuemingzhu
我的博客: http://fuxuemingzhu.cn/java


[LeetCode]node

題目地址:https://leetcode.com/problems/same-tree/python

Total Accepted: 126017 Total Submissions: 291619 Difficulty: Easy算法

題目描述

Given two binary trees, write a function to check if they are the same or not.ide

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.spa

Example 1:code

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

Example 2:遞歸

Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

Example 3:leetcode

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false

題目大意

判斷兩棵二叉樹是否徹底相等。get

解題方法

這道題是樹的題目,屬於最基本的樹遍歷的問題。

問題要求就是判斷兩個樹是否是同樣,基於先序,中序或者後序遍歷均可以作完成,由於對遍歷順序沒有要求。

這裏咱們主要考慮一下結束條件,若是兩個結點都是null,也就是到頭了,那麼返回true。若是其中一個是null,說明在一棵樹上結點到頭,另外一棵樹結點還沒結束,即樹不相同,或者兩個結點都非空,而且結點值不相同,返回false。最後遞歸處理兩個結點的左右子樹,返回左右子樹遞歸的與結果便可。

這裏使用的是先序遍歷,算法的複雜度跟遍歷是一致的,若是使用遞歸,時間複雜度是O(n),空間複雜度是O(logn)。代碼以下:

/** * 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){//注意是在p/q都不爲空的狀況下有一個爲空,說明另一個不爲空
            return false;
        }
        if(p.val!=q.val){//注意是不相等返回False,相等的話須要繼續進行子節點的判斷
            return false;
        }
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }
}

AC:0ms

遞歸問題最終要的是終止條件!!!必定要萬無一失。


二刷,python。

兩年前的我居然寫了這麼多啊,如今寫一個Python版本的。

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution(object):
    def isSameTree(self, p, q):
        """ :type p: TreeNode :type q: TreeNode :rtype: bool """
        if not p and not q:
            return True
        if not p or not q:
            return False
        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

日期

2016/4/30 1:17:33 2018 年 10 月 8 日 —— 終於開學了。 2018 年 11 月 14 日 —— 很嚴重的霧霾

相關文章
相關標籤/搜索