中序遍历,存入list
def midbianli(root,r):
if not root:
return []
midbianli(root.left,r) //list属于可变类型,函数内修改,外部也被修改
r.append(root.val)
midbianli(root.right,r)
return r
res=midbianli(root,[])
可更改(mutable)与不可更改(immutable)对象
在 python 中,strings, tuples, 和 numbers 是不可更改的对象,而 list,dict 等则是可以修改的对象。
不可变类型:变量赋值 a=5 后再赋值 a=10,这里实际是新生成一个 int 值对象 10,再让 a 指向它,而 5 被丢弃,不是改变 a 的值,相当于新生成了 a。
可变类型:变量赋值 la=[1,2,3,4] 后再赋值 la[2]=5 则是将 list la 的第三个元素值更改,本身la没有动,只是其内部的一部分值被修改了。
python 函数的参数传递:
不可变类型:类似 C++ 的值传递,如 整数、字符串、元组。如 fun(a),传递的只是 a 的值,没有影响 a 对象本身。如果在 fun(a))内部修改 a 的值,则是新生成来一个 a。
可变类型:类似 C++ 的引用传递,如 列表,字典。如 fun(la),则是将 la 真正的传过去,修改后 fun 外部的 la 也会受影响
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
深度优先遍历
def preorder_dg(root): #递归
if root==None:
return
print(root.val)
preorder_dg(root.left)
preorder_dg(root.right)
def preorder_dd(root): #迭代
stack = [root]
while stack:
s=stack.pop()
if s!=None:
print(s.val)
stack.append(s.right) #先进后出
stack.append(s.left)
def inorder_dg(root):
if root==None:
return
inorder_dg(root.left)
print(root.val)
inorder_dg(root.right)
def inorder_dd(root):
stack=[]
while root or stack: #右子节点存在或存在记录的节点未处理
while root: #将root与root的左子节点入栈,直到root=None
stack.append(root)
root=root.left
root=stack.pop() #此节点无左子节点 或左子树已处理完
print(root.val)
root=root.right #若存在,记录该节点右子树的左子节点
def postorder_dg(root):
if root==None:
return
postorder_dg(root.left)
postorder_dg(root.right)
print(root.val)
def postorder_dd(root):
stack=[]
while root or stack:
while root:
stack.append(root)
if root.left:
root = root.left
else:
root = root.right
root = stack.pop()
print(root.val)
if stack and root==stack[-1].left: #若root为左子节点,则遍历右子树
root=stack[-1].right
else: #若root为右子节点,则父节点出栈打印
root=None
广度优先遍历
def bfs(root):
queue=[root]
while len(queue)>0:
q=queue.pop(0) #使queue先进先出
print(q.val)
if q.left:
queue.append(q.left)
if q.right:
queue.append(q.right)
广度优先,分层保存:
def maxDepth(self, root: TreeNode) -> int: #
if not root:
return 0
queue=[[root]]
while queue[-1]:
queue.append([])
for q in queue[-2]:
if q.left:
queue[-1].append(q.left)
if q.right:
queue[-1].append(q.right)
return len(queue)-1
其他
#二叉树根节点到叶子节点的所有路径
def path(root):
if root==None:
return []
if root.left==None and root.right==None:
return [[root.val]]
left,right=[],[]
if root.left:
for x in path(root.left):
left.append([root.val]+x)
if root.right:
for x in path(root.right):
right.append([root.val]+x)
return left+right
def treeNodeToString(root):
if not root:
return "[]"
output = ""
queue = [root]
current = 0
while current != len(queue):
node = queue[current]
current = current + 1
if not node:
output += "null, "
continue
output += str(node.val) + ", "
queue.append(node.left)
queue.append(node.right)
return "[" + output[:-2] + "]"
def stringToTreeNode(input):
input = input.strip()
input = input[1:-1]
if not input:
return None
inputValues = [s.strip() for s in input.split(',')]
root = TreeNode(int(inputValues[0]))
nodeQueue = [root]
front = 0
index = 1
while index < len(inputValues):
node = nodeQueue[front]
front = front + 1
item = inputValues[index]
index = index + 1
if item != "null":
leftNumber = int(item)
node.left = TreeNode(leftNumber)
nodeQueue.append(node.left)
if index >= len(inputValues):
break
item = inputValues[index]
index = index + 1
if item != "null":
rightNumber = int(item)
node.right = TreeNode(rightNumber)
nodeQueue.append(node.right)
return root
def prettyPrintTree(node, prefix="", isLeft=True):
if not node:
print("Empty Tree")
return
if node.right:
prettyPrintTree(node.right, prefix + ("│ " if isLeft else " "), False)
print(prefix + ("└── " if isLeft else "┌── ") + str(node.val))
if node.left:
prettyPrintTree(node.left, prefix + (" " if isLeft else "│ "), True)
def main():
import sys
def readlines():
for line in sys.stdin:
yield line.strip('\n')
lines = readlines()
while True:
try:
line = next(lines)
node = stringToTreeNode(line)
prettyPrintTree(node)
preorder_dg(node)
print("-------")
preorder_dd(node)
print("-------")
inorder_dg(node)
print("-------")
inorder_dd(node)
print("-------")
postorder_dg(node)
print("-------")
postorder_dd(node)
except StopIteration:
break
if __name__ == '__main__':
main()