feat(leetcode; utils): 94.二叉树的中序遍历

94.二叉树的中序遍历

Signed-off-by: Ching <loooching@gmail.com>
This commit is contained in:
Ching 2022-01-23 16:22:06 +08:00
parent 091b0e8792
commit b447d032a7
5 changed files with 153 additions and 1 deletions

2
.gitignore vendored
View File

@ -86,7 +86,7 @@ ipython_config.py
# pyenv # pyenv
# For a library or package, you might want to ignore these files since the code is # For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in: # intended to run in multiple environments; otherwise, check them in:
# .python-version .python-version
# pipenv # pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.

15
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,15 @@
{
// 使 IntelliSense
//
// 访: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: 当前文件",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}

17
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,17 @@
{
"python.formatting.provider": "black",
"python.formatting.blackArgs": [
"-S",
"-C",
"-l 120"
],
"editor.formatOnPaste": true,
"editor.formatOnSave": true,
"editor.rulers": [
120
],
"editor.bracketPairColorization.enabled": true,
"editor.guides.bracketPairs": "active",
"vetur.format.options.tabSize": 4,
"vetur.format.enable": false
}

View File

@ -0,0 +1,57 @@
#
# @lc app=leetcode.cn id=94 lang=python3
#
# [94] 二叉树的中序遍历
#
# 中序遍历LDR是二叉树遍历的一种也叫做中根遍历、中序周游。在二叉树中
# 中序遍历首先遍历左子树,然后访问根结点,最后遍历右子树。
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from typing import Optional, List
from utils import *
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
stack = []
if root:
stack.append(root)
while stack:
node = stack[-1]
if node:
# 将该节点弹出,避免重复操作,下面再将右中左节点添加到栈中
stack.pop()
# 添加右节点(空节点不入栈)
if node.right:
stack.append(node.right)
# 添加中节点
stack.append(node)
# 中节点访问过,但是还没有处理,加入空节点作为标记
stack.append(None)
# 添加左节点(空节点不入栈)
if node.left:
stack.append(node.left)
else: # 只有在遇到空节点的时候,才将下一个节点放进结果集中
# 将空节点弹出
stack.pop()
# 重新取出栈中元素
node = stack.pop()
res.append(node.val)
return res
s = Solution()
root = creatBTree([1, None, 2], 0)
s.inorderTraversal(root)
# @lc code=end

63
utils/__init__.py Normal file
View File

@ -0,0 +1,63 @@
# -*- coding: UTF-8 -*-
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __repr__(self):
return 'node %s' % self.val
def creatBTree(data, index):
"""通过数组生成二叉树
Args:
data ([int, None]): 每个节点都要定义包括空节点 eg. [1,None,2, None, None, 3]
index (int): 返回哪个位置的节点
Returns:
TreeNode: TreeNode obj
"""
pNode = None
if index < len(data):
if data[index] == None:
return
pNode = TreeNode(data[index])
pNode.left = creatBTree(data, 2 * index + 1) # [1, 3, 7, 15, ...]
pNode.right = creatBTree(data, 2 * index + 2) # [2, 5, 12, 25, ...]
return pNode
def generate_tree(vals):
"""通过 leetcode 样式的数组生成二叉树
Args:
vals ([int, None]): leetcode 格式省略全空子节点 eg. [1, None, 2, 3]
Returns:
TreeNode: TreeNode obj
"""
if not vals:
return None
que = []
fill_left = True
for val in vals:
node = TreeNode(val) if val else None
if len(que) == 0:
root = node
que.append(node)
elif fill_left:
que[0].left = node
fill_left = False
if node:
que.append(node)
else:
que[0].right = node
if node:
que.append(node)
que.pop(0)
fill_left = True
return root