https://leetcode.cn/problems/n-ary-tree-preorder-traversal/
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def __init__(self):
self.ans = []
def traverse(self, root: 'Node'):
if root == None:
return
self.ans.append(root.val)
for child in root.children:
self.traverse(child)
def preorder(self, root: 'Node') -> List[int]:
self.traverse(root)
return self.ans
迭代的方法之后再补充!
https://leetcode.cn/problems/n-ary-tree-postorder-traversal/
# 改一下traverse即可
def traverse(self, root: 'Node'):
if root == None:
return
for child in root.children:
self.traverse(child)
self.ans.append(root.val)
https://leetcode.cn/problems/binary-tree-inorder-traversal/
给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。
class Solution:
def traverse(self, root, orders):
if root == None:
return
self.traverse(root.left, orders)
orders.append(root.val)
self.traverse(root.right, orders)
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
orders = []
self.traverse(root, orders)
return orders
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],返回深度为3
递归方法
# 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
class Solution:
def maxDepth(self, root: Optional[TreeNode]):
if root == None:
return 0
leftVal = self.maxDepth(root.left)
rightVal = self.maxDepth(root.right)
return 1 + max(leftVal, rightVal)
另一种方法。
class Solution:
def travese(self, root, depth):
if root == None:
return
# 表示向下一层
depth += 1
self.res = max(self.res, depth)
self.travese(root.left, depth)
self.travese(root.right, depth)
# 退回
depth -= 1
def maxDepth(self, root: Optional[TreeNode]):
self.res = 0
self.travese(root, 0)
return self.res