二叉樹的前序遍歷,中序遍歷和後序遍歷(python實現)
阿新 • • 發佈:2019-02-17
# 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 preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if root == None: return [] resLs = [] stack,node = [],root while stack.__len__() > 0 or node!=None: while node != None: resLs.append(node.val) stack.append(node) node = node.left node = stack.pop() node = node.right return resLs
後序遍歷(基本思想:通過層次遍歷,總是先列印右節點,然後再使用一次倒序來列印所有結果;例如存在樹結構1->2,1->3,2->4,2->5,3->6,3->7;可以按照順序(1,3,2,7,6,5,4)的順序將結果儲存起來,然後再進行一次逆序就得到正確結果)# 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 inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if root == None: return [] stack,node = [],root resLs = [] while stack.__len__() > 0 or node!=None: while node!=None: ###向左葉子節點遍歷直到最底層 stack.append(node) node = node.left node = stack.pop() resLs.append(node.val) node = node.right return resLs
輸入一個整數陣列,判斷該陣列是不是某二叉搜尋樹的後序遍歷的結果。如果是則輸出Yes,否則輸出No。假設輸入的陣列的任意兩個數字都互不相同。(基本思想:二叉搜尋樹滿足左子節點值都小於根節點值,右子節點值都大於根節點值;後序遍歷的最後一個元素是根節點,序列中小於根節點的所有數構成左子樹,大於根節點的所有數構成右子樹)# 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 postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if root == None: return [] stack,node = [root],root resLs = [] while stack.__len__()>0: node = stack.pop() resLs.append(node.val) if node.left != None: stack.append(node.left) if node.right != None: stack.append(node.right) return [val for val in reversed(resLs)]
# -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
if len(sequence)==0:
return False
index = 0
for index in xrange(len(sequence)-1): ###找出左子樹
if sequence[index]>sequence[-1]:
break
for i in xrange(index+1,len(sequence)-1): ###判斷右子樹的數是否比根節點大
if sequence[i]<sequence[-1]:
return False
if self.check(sequence,0,index) and self.check(sequence,index+1,len(sequence)-1):
return True
else:
return False
def check(self,sequence,start,end):
if start>=end:
return True
index = 0
for index in xrange(start,end):
if sequence[index]>sequence[end]:
break
for i in xrange(index+1,end):
if sequence[i]<sequence[end]:
return False
return self.check(sequence,start,index) and self.check(sequence,index+1,end-1)