为了方便大家理解和记忆,都是采用最容易理解以及代码量最少的写法,尽量pythonic.
二叉树的前序遍历指的是(中—> 左 —> 右)。实现非递归算法的主要思路就是队列和栈。但是由于栈后进先出的特性,所以先压入栈的时候,先压入右孩子, 再压入左孩子。
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
中序遍历的意思就是(左—> 中 —> 右)的顺序遍历
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
后序遍历的意思就是(左—> 右 —> 中)的顺序遍历
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
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
# 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
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
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)