Leetcode之二叉樹(前200道)

持續更新...

github鏈接:https://github.com/x2mercy/Leetcode_Solution

?

為什么括號200道呢!因為準備按照200道這樣的周期刷,每200道刷兩遍,第一遍按難度刷,第二遍按類別刷!

先整理binarytree這一類別也是因為在刷題的過程中,由于沒有系統的算法基礎,這類題目算是遇到的比較大的障礙。

下面按照題目難度來說:

——————————————————————————————————————————————————————————————————————————————————————

EASY:

1. Same Tree:

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

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

這是我做的第一道二叉樹的題目。

一開始的思路是二叉樹的遍歷,找到的資料:http://blog.csdn.net/bone_ace/article/details/46718683 主要說了樹的構造和幾種遍歷方式

所以第一種方法是用層次遍歷做的,代碼如下:

# this solution is Time Limit Exceeded
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution(object):def isSameTree(self, p, q):""":type p: TreeNode:type q: TreeNode:rtype: bool"""result1=[]result1.append(p.val)while p:if p.left!=None:result1.append(p.left)if p.right!=None:result1.append(p.right)result2=[]result2.append(q.val)while q:if q.left!=None:result1.append(q.left)if q.right!=None:result1.append(q.right)result=cmp(result1,result2)if result==0:return Trueelse:return False

滿心歡喜的以為可以過,但是卻報了time limit exceed的錯誤,于是開始找第二種方法!

上代碼:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution(object):def isSameTree(self, p, q):""":type p: TreeNode:type q: TreeNode:rtype: bool"""if p==None and q==None:return Trueif p==None or q==None:return Falseif p.val==q.val:return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)return False

這種做法寫完之后呢。。emmmm覺得自己上一種方法簡直是智障兒童

這種方法很簡單吶,重點是用了遞歸。遞歸真是一種邏輯簡潔的好東西,利用遞歸比較子樹的各個節點是否相同。

2. Symmetric Tree:

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

先上代碼:

# recursive answer
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution(object):def isSymmetric(self, root):""":type root: TreeNode:rtype: bool"""if root==None:return Truereturn self.isMirror(root.left,root.right)def isMirror(self,p,q):if p==None and q==None:return Trueif p==None or q==None:return Falsereturn p.val==q.val and self.isMirror(p.left,q.right) and self.isMirror(p.right,q.left)

這道題的重點在于調用了另一個函數,因為需要比較是否對稱的本質是比較左子樹的左節點和右子樹的右節點、左子樹的右節點和右子樹的左節點是否相等,所以需要調用IsMirror函數,可以接收兩個arg,isMirror返回的boolean值主要由節點值是否相等以及下個節點是否對稱來決定,所以這里用了遞歸。

注意:用了遞歸,就一定要有遞歸停止的條件,不能無限循環下去

3.??Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

這道題算法很經典,mark一下,可以用在很多二叉樹的題目中。

上代碼:

#iterator
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution(object):def maxDepth(self, root):""":type root: TreeNode:rtype: int"""if root==None:return 0DL=self.maxDepth(root.left)DR=self.maxDepth(root.right)return max(DL,DR)+1

后面還有一道求最短路徑的題目,和這個做法類似

主要也是用了遞歸,最后返回的時候注意要+1,因為返回的是節點數

4.?Binary Tree Level Order Traversal II

Given a binary tree, return the?bottom-up level order?traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution(object):def levelOrderBottom(self, root):""":type root: TreeNode:rtype: List[List[int]]"""if root==None:return []p=collections.deque()p.append((root,0))result=[]while p:node,index=p.popleft()if index>len(result)-1:result.append([node.val])else:result[index].append(node.val)if node.left:p.append((node.left,index+1))if node.right:p.append((node.right,index+1))result.reverse()return result        

這里本來想用queue,但是發現了一個很神奇的東西:deque(學疏才淺。。),是python標準庫里的一項,直接from collections import deque,或者像我這樣collections.deque就可以用了。

它的好處在于,它可以提供類似于list的操作,比如append什么的,但是不同的是可以popleft操作,使第一位元素pop出來。(參考:http://blog.csdn.net/qins_superlover/article/details/44338415)

這一種操作對解決二叉樹問題,提供了很大的幫助!比如這道題!

這道題是讓我們把整個二叉樹倒過來,返回從最底層到最上層的節點,給的例子是這樣的:

?于是我們知道了在append節點時,需要注意把它的index也append進去,這樣便于后面判斷是不是同一層的節點。

因為父節點下面的兩個子節點的index是一樣的,所以在append左邊節點之后,會出現len(result)-1是大于右邊節點index的,這時直接把右邊節點append到result[index]中,等于是個多維array

最后再reverse一下,返回,搞定

5.?Convert Sorted Array to Binary Search Tree:

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

這里第一次遇到平衡二叉樹,所謂平衡二叉樹要滿足幾個條件:它是一棵空樹或它的左右兩個子樹的高度差的絕對值不超過1,并且左右兩個子樹都是一棵平衡二叉樹

所以又要用到遞歸

上代碼:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution(object):def sortedArrayToBST(self, nums):""":type nums: List[int]:rtype: TreeNode"""if nums==[]:return Nonemid=len(nums)//2root=TreeNode(nums[mid])root.left=self.sortedArrayToBST(nums[:mid])root.right=self.sortedArrayToBST(nums[mid+1:])return root

?

?其實這道題很簡單,核心就是要找到根節點,而因為是sortedarray所以要找根節點,就直接找中間的那個元素,為了避免麻煩,用了"//",表示取商的整數部分

然后分別對左子樹和右子樹用遞歸,這里的nums[:mid]和nums[mid+1:],表示nums從下標為0到mid(不包括mid),nums從下標mid+1到最后

6.?Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of?every?node never differ by more than 1.

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution(object):def isBalanced(self, root):""":type root: TreeNode:rtype: bool"""if root==None:return TrueDL=self.depth(root.left)DR=self.depth(root.right)if DL-DR<-1 or DL-DR>1:return Falsereturn self.isBalanced(root.left) and self.isBalanced(root.right)def depth(self,node):if node==None:return 0DL=self.depth(node.left)DR=self.depth(node.right)return max(DL,DR)+1

?這里要注意的是判斷是否為平衡二叉樹,需要考慮一個節點左右子樹是否都為平衡二叉樹,所以在返回時需要用and來實現

調用了depth函數(前面說了,這個函數很經典很常用)

然后就是在比較高度時,要注意-1的情況

7.?Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution(object):def minDepth(self, root):""":type root: TreeNode:rtype: int"""if root==None:return 0DL=self.minDepth(root.left)DR=self.minDepth(root.right)d=min(DL,DR)D=max(DL,DR)if DL==0 or DR==0:return D+1else:return d+1

看吧,這個算法真的很常用

但是要注意的是:如果某一子樹路徑為0, 則取左右子樹中最大的那個,如果都不為0,則取左右子樹中最小的那個

8. Path Sum:

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution(object):def hasPathSum(self, root, sum):""":type root: TreeNode:type sum: int:rtype: bool"""if root==None:return Falseif root.right==None and root.left==None and root.val==sum:return Truesum=sum-root.valreturn self.hasPathSum(root.left,sum) or self.hasPathSum(root.right,sum)
這道題最開始想復雜了,一直在想用deque(),然后一個一個節點加,但其實不用,cheat了一下,看了dicuss,發現了機智的做法!
只需要依次比較每個節點,比較完之后,sum減去這個節點,然后比較下一個(左或者右),直到sum=某個節點,則返回true
否則返回false
重點在于每次都需要sum減去這個節點值!這樣如果剩下的節點值等于這個數,并且!它沒有左右子樹,則返回true

?————————————————————————————————————————————————————————————————————————————————————

?

轉載于:https://www.cnblogs.com/x1mercy/p/7802167.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/252957.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/252957.shtml
英文地址,請注明出處:http://en.pswp.cn/news/252957.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

在ARM Linux下使用GPIO模擬SPI時序詳解

Author&#xff1a;楊正 Data&#xff1a;2016.1.1 Mail&#xff1a;yz2012wwgmail.com一、 概述 SPI是英文SerialPeripheral Interface的縮寫&#xff0c;顧名思義就是串行外圍設備接口。SPI是一種高速、全雙工、同步通信總線&#xff0c;標準的SPI有4個引腳&#xff…

git clone時出現 error:inflate:data stream error(incorrect data check)

git clone時出現 error:inflate:data stream error(incorrect data check) fatal:serrious inflate inconsistency fatal:index-pack failed 經了解&#xff0c;此問題是遺留問題&#xff0c;之前是因為公司對gitlab服務器進行數據遷移而引起這種git clone失敗的原因&#xff0…

CentOS 7.5 使用 yum 安裝 Kubernetes 集群(二)

一、安裝方式介紹 1、yum 安裝 目前CentOS官方已經把Kubernetes源放入到自己的默認 extras 倉庫里面&#xff0c;使用 yum 安裝&#xff0c;好處是簡單&#xff0c;壞處也很明顯&#xff0c;需要官方更新 yum 源才能獲得最新版本的軟件&#xff0c;而所有軟件的依賴又不能自己指…

zbb20171108 tomcat 性能優化

原文地址http://www.cnblogs.com/NiceTime/p/6665416.html 1)內存優化(調整配置堆的大小&#xff0c;修改文件&#xff1a;catalina.sh) JAVA_OPTS"-Djava.awt.headlesstrue -Dfile.encodingUTF-8 -server -XX:MinHeapFreeRatio80 -XX:MaxHeapFreeRatio80 -XX:ThreadStack…

深入理解pthread_cond_wait、pthread_cond_signal

man pthread_cond_wait的解釋 LINUX環境下多線程編程肯定會遇到需要條件變量的情況&#xff0c;此時必然要使用pthread_cond_wait()函數。但這個函數的執行過程比較難于理解。 pthread_cond_wait()的工作流程如下&#xff08;以MAN中的EXAMPLE為例&#xff09;&#xff1a;…

LeetCode算法題-Factorial Trailing Zeroes(Java實現)

這是悅樂書的第183次更新&#xff0c;第185篇原創 01 看題和準備 今天介紹的是LeetCode算法題中Easy級別的第42題&#xff08;順位題號是172&#xff09;。給定一個整數n&#xff0c;返回n&#xff01;中的尾隨零數。例如&#xff1a; 輸入&#xff1a;3 輸出&#xff1a;0 說明…

JavaWeb基礎—JS學習小結

JavaScript是一種運行在瀏覽器中的解釋型的編程語言 推薦&#xff1a;菜鳥教程一、簡介js:javascript是基于對象【哪些基本對象呢】和和事件驅動【哪些主要事件呢】的語言&#xff0c;應用在客戶端&#xff08;注意與面向對象的區分&#xff09; js的三大特點&#xff1a;  交…

Asp.Net 設計模式 之 “簡單工廠”模式

主要思想&#xff1a;public static Operation CreateFactory(string ope) { //實例化空父類&#xff0c;讓父類指向子類 Operation op null; switch (ope) { case "": op …

UBuntu國內鏡像地址下載

http://www.oschina.net/p/ubuntu http://releases.ubuntu.com/ http://mirrors.163.com/ubuntu-releases/14.04/

Effective_STL 學習筆記(十九) 了解相等和等價的區別

find 算法和 set 的 insert 成員函數是很多必須判斷兩個值是否相同的函數代表&#xff0c; find 對 “相同” 的定義是相等&#xff0c;基于 operator &#xff0c; set::insert 對 “相同” 的定義是等價&#xff0c;通常基于 operator< 。 操作上來說&#xff0c;相等的概…

判斷是否獲取到手機相機權限

實際運用場景&#xff1a; 上傳圖片&#xff0c;查看相機設備&#xff0c;使用相機 在做這些操作的時候先調用這段話 AVAuthorizationStatus authStatus [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]; if (authStatus AVAuthorizationStatusRestric…

事物筆記

什么是事務&#xff1a; 一件事情有N個組成單元&#xff0c;執行之后要么同時成功&#xff0c;要么同時失敗。 MySQL是一條默認的事務&#xff0c;一條sql語句就是一條事務。------------------------------------------------------------MySQL事務&#xff1a; 1、開啟一個事…

Python Socket通信黏包問題分析及解決方法

參考&#xff1a;http://www.cnblogs.com/Eva-J/articles/8244551.html#_label5 1.黏包的表現(以客戶端遠程操作服務端命令為例) 注&#xff1a;只有在TCP協議通信的情況下&#xff0c;才會產生黏包問題 基于TCP協議實現的黏包 #!/usr/bin/env python # -*- coding: utf-8 -*- …

Django 路由

定義&#xff1a; URL配置(URLconf)就像Django 所支撐網站的目錄。它的本質是URL與要為該URL調用的視圖函數之間的映射表&#xff1b;你就是以這種方式告訴Django&#xff0c;對于這個URL調用這段代碼&#xff0c;對于那個URL調用那段代碼。 URL配置格式&#xff1a; urlpatter…

Ubuntu默認不進入圖形界面

修改 /etc/X11/default-display-manager如果值為/usr/sbin/gdm&#xff0c;(ubuntu12.04 為/usr/sbin/lightdm)則進入圖形界面 如果值為false&#xff0c;則進入控制臺&#xff08;命令行方式&#xff09;。如果想從控制臺進入圖形界面&#xff0c;可以在控制臺上輸入命令 sudo…

讀《構建之法》的心得體會

前段時間&#xff0c;我看了《構建之法》的一些內容&#xff0c;有了一些心得體會。 軟件工程所討論的是代碼量巨大、涉及人數眾多、項目需求多變時所要解決的問題。而在校學生根本就沒有這樣的環境。而鄒欣老師的《構建之法》是我讀過的書中最淺顯易懂的軟件工程書。 在緒論中…

2440內存管理

title: 2440內存管理 tags: ARM date: 2018-10-17 19:08:49 --- 2440內存管理 特性 大/小端&#xff08;通過軟件選擇&#xff09;地址空間&#xff1a;每個 Bank 有 128M 字節(總共 1G/8 個 Bank)除了 BANK0&#xff08;16/32 位&#xff09;之外【引導ROM&#xff0c;其總線寬…

C#設計模式之十二代理模式(Proxy Pattern)【結構型】

一、引言 今天我們要講【結構型】設計模式的第七個模式&#xff0c;也是“結構型”設計模式中的最后一個模式&#xff0c;該模式是【代理模式】&#xff0c;英文名稱是&#xff1a;Proxy Pattern。還是老套路&#xff0c;先從名字上來看看。“代理”可以理解為“代替”&#…

IPv6檢測

1&#xff09;判斷服務器是否支持IPv6 &#xff1a; http://ipv6-test.com/validate.php 2&#xff09;檢測當前設備打開網站的連接方式是IPv4還是IPv6&#xff1a; http://ipv6.sjtu.edu.cn/ 轉載于:https://www.cnblogs.com/superbobo/p/6687605.html

百度首席科學家吳恩達宣布將從百度離職

海外網3月22日電 據媒體消息&#xff0c;百度首席科學家吳恩達&#xff08;Andrew Ng&#xff09;在英文自媒體平臺Medium及微博、Twitter等個人社交平臺發布公開信&#xff0c;宣布自己將從百度離職&#xff0c;開啟自己在人工智能領域的新篇章。 吳恩達是人工智能和機器學習…