-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary-tree-dfs.py
68 lines (56 loc) · 1.46 KB
/
binary-tree-dfs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File name : binary-tree-dfs.py
Author : miaoyc
Create date : 2021/11/11 12:36 上午
Description : 二叉树问题处理模板
"""
"""
此模板为递归处理模板
二叉树遍历问题,首先要找到递归处理的退出条件,其次找到遍历顺序和对节点的处理
经典的二叉树前中后序三种遍历
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def action(self, root):
# 对节点的处理,此处打印仅为举例
print(root.val)
def preorder(self, root):
"""
前序遍历
:param root:
:return:
"""
if not root:
return
self.result.append(root.val)
self.preorder(root.left)
self.preorder(root.right)
def inorder(self, root):
"""
中序遍历
:param root:
:return:
"""
# 退出条件,此处root节点不存在仅为举例
if not root:
return
self.inorder(root.left)
self.action(root)
self.inorder(root.right)
def postorder(self, root):
"""
后序遍历
:param root:
:return:
"""
if not root:
return
self.postorder(root.left)
self.postorder(root.right)
self.result.append(root.val)