天天分享一個LeetCode題目node
天天 5 分鐘,一塊兒進步python
LeetCode N 叉樹的前序遍歷,地址: leetcode-cn.com/problems/n-…數組
class TreeNode(object):
def __init__(self, val, children=[]):
self.val = val
self.children = children
複製代碼
利用遞歸,依然遵循「跟左右」的遍歷原則markdown
def preorder(self, root):
print(root.val, end=" ")
for node in root.children:
self.preorder(node)
複製代碼
是否是看起來特別簡單,可是這樣不符合 LeetCode 題目中的要求app
須要將結果放到一個數組中,因此須要提早初始化一個 list 進行存放oop
從新編碼看看ui
def preorder(self, root):
# print(root.val, end=" ")
# for node in root.children:
# self.preorder(node)
res = []
def dfs(root):
if not root:
return
res.append(root.val)
for node in root.children:
dfs(node)
dfs(root)
return res
複製代碼
就是提早初始化了 res,而後在遍歷的時候進賦值操做編碼
可直接執行spa
# -*- coding:utf-8 -*-
# !/usr/bin/env python
# 樹結點類
class Node(object):
def __init__(self, val=None, children=[]):
self.val = val
self.children = children
class Solution(object):
def preorder(self, root):
# print(root.val, end=" ")
# for node in root.children:
# self.preorder(node)
res = []
def dfs(root):
if not root:
return
res.append(root.val)
for node in root.children:
dfs(node)
dfs(root)
return res
if __name__ == "__main__":
# 新建節點
root = Node('A')
node_B = Node('B')
node_C = Node('C')
node_D = Node('D')
node_E = Node('E')
node_F = Node('F')
node_G = Node('G')
node_H = Node('H')
node_I = Node('I')
# 構建三叉樹
# A
# / | \
# B C D
# /|\ / \
# E F G H I
root.children = [node_B, node_C, node_D]
node_B.children = [node_E, node_F, node_G]
node_D.children = [node_H, node_I]
s = Solution()
print(s.preorder(root))
複製代碼
玩的開心呀 ღ( ´・ᴗ・` )code