刻意練習:LeetCode實戰 -- Task20. 對稱二叉樹

背景

本篇圖文是LSGO軟件技術團隊組織的 第二期基礎算法(Leetcode)刻意練習訓練營 的打卡任務。本期訓練營採用分類別練習的模式,即選擇了五個知識點(數組、鏈表、字符串、樹、貪心算法),每個知識點選擇了 三個簡單、兩個中等、一個困難 等級的題目,共計三十道題,利用三十天的時間完成這組刻意練習。

本次任務的知識點:樹

是一種抽象數據類型(ADT)或是實現這種抽象數據類型的數據結構,用來模擬具有樹狀結構性質的數據集合。它是由 n(n>0) 個有限節點組成的一個具有層次關係的集合。

把它叫做「樹」是因爲它看起來像一棵倒掛的樹,也就是說它是根朝上,而葉朝下的。

它具有以下的特點:

  • 每個節點都只有有限個子節點或無子節點;
  • 沒有父節點的節點稱爲根節點;
  • 每一個非根節點有且只有一個父節點;
  • 除了根節點外,每個子節點可以分爲多個不相交的子樹;
  • 樹裏面沒有環路。

題目

  • 題號:101
  • 難度:簡單
  • https://leetcode-cn.com/problems/symmetric-tree/

給定一個二叉樹,檢查它是否是鏡像對稱的。

例如,二叉樹 [1,2,2,3,4,4,3] 是對稱的。

    1
   / \
  2   2
 / \ / \
3  4 4  3

但是下面這個 [1,2,2,null,3,null,3] 則不是鏡像對稱的:

    1
   / \
  2   2
   \   \
   3    3

實現

第一種:採用遞歸的方法

  • 執行結果:通過
  • 執行用時:132 ms, 在所有 C# 提交中擊敗了 16.67% 的用戶
  • 內存消耗:25.1 MB, 在所有 C# 提交中擊敗了 5.17% 的用戶
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
 
//鏡像對稱的遞歸函數
public class Solution
{
    public bool IsSymmetric(TreeNode root)
    {
        return IsMirror(root, root);
    }
    private bool IsMirror(TreeNode t1, TreeNode t2)
    {
        if (t1 == null && t2 == null) return true;
        if (t1 == null || t2 == null) return false;
        return (t1.val == t2.val)
            && IsMirror(t1.left, t2.right)
            && IsMirror(t1.right, t2.left);
    }
}

Python 語言

  • 執行結果:通過
  • 執行用時:48 ms, 在所有 Python3 提交中擊敗了 30.95% 的用戶
  • 內存消耗:13.7 MB, 在所有 Python3 提交中擊敗了 5.17% 的用戶
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        return self.isMirror(root, root)

    def isMirror(self, t1: TreeNode, t2: TreeNode) -> bool:
        if t1 is None and t2 is None:
            return True
        if t1 is None or t2 is None:
            return False
        return t1.val == t2.val and self.isMirror(t1.left, t2.right) and self.isMirror(t1.right, t2.left)

第二種:採用隊列的方法

思路:利用二叉樹的層次遍歷的方式來實現。

  • 執行結果:通過
  • 執行用時:112 ms, 在所有 C# 提交中擊敗了 70.93% 的用戶
  • 內存消耗:24.9 MB, 在所有 C# 提交中擊敗了 5.17% 的用戶
public class Solution
{
    public bool IsSymmetric(TreeNode root)
    {
        if (root == null)
            return true;

        Queue<TreeNode> nodes = new Queue<TreeNode>();
        nodes.Enqueue(root.left);
        nodes.Enqueue(root.right);
        while (nodes.Count != 0)
        {
            TreeNode node1 = nodes.Dequeue();
            TreeNode node2 = nodes.Dequeue();

            if (node1 == null && node2 == null)
                continue;
            if (node1 == null || node2 == null)
                return false;
            if (node1.val != node2.val)
                return false;
            nodes.Enqueue(node1.left);
            nodes.Enqueue(node2.right);
            nodes.Enqueue(node1.right);
            nodes.Enqueue(node2.left);
        }
        return true;
    }
}

往期活動

LSGO軟件技術團隊會定期開展提升編程技能的刻意練習活動,希望大家能夠參與進來一起刻意練習,一起學習進步!


我是 終身學習者“老馬”,一個長期踐行“結伴式學習”理念的 中年大叔

我崇尚分享,渴望成長,於2010年創立了“LSGO軟件技術團隊”,並加入了國內著名的開源組織“Datawhale”,也是“Dre@mtech”、“智能機器人研究中心”和“大數據與哲學社會科學實驗室”的一員。

願我們一起學習,一起進步,相互陪伴,共同成長。

後臺回覆「搜搜搜」,隨機獲取電子資源!
歡迎關注,請掃描二維碼:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章