589. N 叉树的前序遍历
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
迭代的方法之后再补充!
590. N 叉树的后序遍历
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)
94. 二叉树的中序遍历
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
104. 二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [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
100. 相同的树
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if p == None and q == None:
return True
if p == None or q == None:
return False
if p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)