2023-04-16 04:52:42 +08:00
|
|
|
"""
|
2023-04-23 19:36:07 +08:00
|
|
|
File: preorder_traversal_iii_compact.py
|
2023-04-16 04:52:42 +08:00
|
|
|
Created Time: 2023-04-15
|
|
|
|
Author: Krahets (krahets@163.com)
|
|
|
|
"""
|
|
|
|
|
|
|
|
import sys, os.path as osp
|
|
|
|
|
|
|
|
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
|
|
|
|
from modules import *
|
|
|
|
|
|
|
|
|
2023-07-24 22:34:05 +08:00
|
|
|
def pre_order(root: TreeNode):
|
2023-04-22 01:38:53 +08:00
|
|
|
"""前序遍历:例题三"""
|
2023-04-16 04:52:42 +08:00
|
|
|
# 剪枝
|
|
|
|
if root is None or root.val == 3:
|
|
|
|
return
|
|
|
|
# 尝试
|
|
|
|
path.append(root)
|
|
|
|
if root.val == 7:
|
|
|
|
# 记录解
|
|
|
|
res.append(list(path))
|
2023-07-21 22:08:26 +08:00
|
|
|
path.pop()
|
2023-07-19 16:37:12 +08:00
|
|
|
return
|
2023-04-16 04:52:42 +08:00
|
|
|
pre_order(root.left)
|
|
|
|
pre_order(root.right)
|
|
|
|
# 回退
|
|
|
|
path.pop()
|
|
|
|
|
|
|
|
|
|
|
|
"""Driver Code"""
|
|
|
|
if __name__ == "__main__":
|
|
|
|
root = list_to_tree([1, 7, 3, 4, 5, 6, 7])
|
|
|
|
print("\n初始化二叉树")
|
|
|
|
print_tree(root)
|
|
|
|
|
|
|
|
# 前序遍历
|
|
|
|
path = list[TreeNode]()
|
|
|
|
res = list[list[TreeNode]]()
|
|
|
|
pre_order(root)
|
|
|
|
|
2023-07-25 16:39:38 +08:00
|
|
|
print("\n输出所有根节点到节点 7 的路径,路径中不包含值为 3 的节点")
|
2023-04-16 04:52:42 +08:00
|
|
|
for path in res:
|
|
|
|
print([node.val for node in path])
|