二叉树的前序,中序,后序,层序遍历(python写法总结, python 面试必备)

二叉树的前序,中序,后序,层序遍历(python非递归写法总结, python 面试必备)

为了方便大家理解和记忆,都是采用最容易理解以及代码量最少的写法,尽量pythonic.

二叉树的前序遍历(leetcode 144)

二叉树的前序遍历指的是(中—> 左 —> 右)。实现非递归算法的主要思路就是队列和栈。但是由于栈后进先出的特性,所以先压入栈的时候,先压入右孩子, 再压入左孩子。

Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
	def preorderTraversal(self, root):
		ret, stack = [], [root]
		while stack:
			node = stack.pop()
			if node:
				ret.append(node.val)
				#注意压入栈的顺序,先压入右孩子,再压入左孩子
				stack.append(node.right)
				stack.append(node.left)
		return ret			

二叉树的前序,中序,后序,层序遍历(python写法总结, python 面试必备)_第1张图片

二叉树中序遍历(leetcode 94)

中序遍历的意思就是(左—> 中 —> 右)的顺序遍历

Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def inorderTraversal(self, root):
        ret, stack = [], []
        while stack or root:
            if root:
	            stack.append(root)
	            root = root.left
	        else:
		        temNode = stack.pop()
		        ret.append(temNode.val)
		        root = temNode.right
		return ret

二叉树的前序,中序,后序,层序遍历(python写法总结, python 面试必备)_第2张图片

二叉树后序遍历(leetcode 145)

后序遍历的意思就是(左—> 右 —> 中)的顺序遍历

解法一

class Solution:
    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        ret, stack = [], []
        while root or stack:
            if root:
                stack.append(root)
                ret.insert(0, root.val)
                root = root.right
            else:
                node = stack.pop()
                root = node.left
        return ret

解法二(更佳)

## 先构造[中->左->右],再翻转为[左->右->中]
def postorderTraversal(self, root):
    res, stack = [], [root]
    while stack:
        node=stack.pop()
        if node:
            res.append(node.val)
            stack.append(node.left)
            stack.append(node.right)
    return res[::-1]

解法三:

def postorderTraversal(self, root):
    res, stack = [], [(root, False)]
    while stack:
        node,visited = stack.pop()
        if node:
            if visited:
                res.append(node.val)
            else:
                stack.append((node, True))
                stack.append((node.right, False))
                stack.append((node.left, False))
     return res

二叉树的前序,中序,后序,层序遍历(python写法总结, python 面试必备)_第3张图片

二叉树层序遍历(leetcode 102)

class Solution:
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        ans, level = [], [root]
        while any(level):
            ans.append([node.val for node in level])            
            level = [kid for n in level for kid in (n.left, n.right) if kid]
        return ans

二叉树的前序,中序,后序,层序遍历(python写法总结, python 面试必备)_第4张图片

多叉树的层序遍历(leetcode 429)

# Definition for a Node.
class Node(object):
    def __init__(self, val, children):
        self.val = val
        self.children = children
class Solution(object):
    def levelOrder(self, root):
        """
        :type root: Node
        :rtype: List[List[int]]
        """
        ret, level = [], [root]
        while any(level):
            ret.append([node.val for node in level])
            level = [child for node in level for child in node.children if child]
        return ret

二叉树的前序,中序,后序,层序遍历(python写法总结, python 面试必备)_第5张图片

树的深度遍历

def deep(root):
   if not root:
       return
   print(root.val)
   deep(root.left)
   deep(root.right)

if __name__ == '__main__':
   deep(tree)

判断两颗树是否相同

def isSample(p,q):
   if p == None and q == None:
       return True
   elif p and q:
       return p.val == q.val and isSample(p.left, q.left) and isSample(p.right, q.right)
   else:
       return False

判断是否为合法的二分搜索树BST(leetcode 98)

def isValidBST(self, root, floor=float('-inf'), ceiling=float('inf')):
    if not root:
        return True
    if root.val < floor or root.val > ceiling:
        return False
    return self.isValidBST(root.left, floor, root.val) and self.isValidBST(root.right, root.val, ceiling)

如有问题,欢迎批评指正 !!!

你可能感兴趣的:(python面试,树的遍历)