#递归法 # 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 classSolution: defpreorderTraversal(self, root: Optional[TreeNode]) -> List[int]: out = [] self.preOrder(root, out) return out
//递归法 /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ funcpreorderTraversal(root *TreeNode) (out []int) { return preOrder(root, out) }
# 递归法 # 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 classSolution: definorderTraversal(self, root: Optional[TreeNode]) -> List[int]: out = []
definorder(node: TreeNode): if node: inorder(node.left) out.append(node.val) inorder(node.right)
inorder(root) return out
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# 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 classSolution: definorderTraversal(self, root: Optional[TreeNode]) -> List[int]: res = [] stack = [] while root or stack: while root: stack.append(root) root = root.left root = stack.pop() res.append(root.val) root = root.right return res
# 递归法 # 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 classSolution: defpostorderTraversal(self, root: Optional[TreeNode]) -> List[int]: out = []
// Check if the right subtree is nil or already visited if top.Right == nil || top.Right == prev { result = append(result, top.Val) stack = stack[:len(stack)-1] prev = top } else { // Move to the right subtree root = top.Right } }
# I. 按层打印: 题目要求的二叉树的 从上至下 打印(即按层打印),又称为二叉树的 广度优先搜索(BFS)。BFS 通常借助 队列 的先入先出特性来实现。 # II. 每层打印到一行: 将本层全部节点打印到一行,并将下一层全部节点加入队列,以此类推,即可分为多行打印。
# 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 classSolution: deflevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: if root isNone: return [] out = [] q = [root] while q: tmp = [] l = len(q) for i inrange(l): node = q.pop(0) tmp.append(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) out.append(tmp) return out
classSolution: deflevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: if root isNone: return [] out = [] q = [root] i = 0 while q: p = [] out.append([]) for j inrange(len(q)): node = q[j] out[i].append(node.val) if node.left: p.append(node.left) if node.right: p.append(node.right) q = p i += 1 return out
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution: deflevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: ifnot root: return [] result = [] queue = [root] while queue: vals = [] next_level = [] for n in queue: vals.append(n.val) if n.left: next_level.append(n.left) if n.right: next_level.append(n.right) result.append(vals) queue = next_level return result
//官方解法 /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ funclevelOrder(root *TreeNode) [][]int { var ret [][]int if root == nil { return ret } q := []*TreeNode{root} for i := 0; len(q) > 0; i++ { ret = append(ret, []int{}) var p []*TreeNode for j := 0; j < len(q); j++ { node := q[j] ret[i] = append(ret[i], node.Val) if node.Left != nil { p = append(p, node.Left) } if node.Right != nil { p = append(p, node.Right) } } q = p } return ret }
# 跟上题解法差不多,层序遍历,首部追加 # 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 classSolution: deflevelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]: if root isNone: return [] out = [] q = [root] while q: tmp = [] l = len(q) for i inrange(l): node = q.pop(0) tmp.append(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) out = [tmp] + out return out
# 先正序再反转 # 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 classSolution: deflevelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]: if root isNone: return [] out = [] q = [root] while q: tmp = [] l = len(q) for i inrange(l): node = q.pop(0) tmp.append(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) out.append(tmp) out.reverse() return out
# 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 classSolution: deflevelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]: if root isNone: return [] out = [] q = [root] while q: tmp = [] l = len(q) for i inrange(l): node = q.pop(0) tmp.append(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) out.append(tmp) return out[::-1]
# 层序遍历的时候,判断是否遍历到单层的最后面的元素,如果是,就放进及如果数组。 # 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 classSolution: defrightSideView(self, root: Optional[TreeNode]) -> List[int]: ifnot root: return [] res, queue = [], collections.deque([root]) while queue: l = len(queue) for i inrange(l): node = queue.popleft() if node.left: queue.append(node.left) if node.right: queue.append(node.right) if i == l - 1: res.append(node.val) return res
# 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 classSolution: defrightSideView(self, root: Optional[TreeNode]) -> List[int]: if root isNone: return [] out = [] q = [root] while q: l = len(q) for i inrange(l): node = q[i] if node.left: q.append(node.left) if node.right: q.append(node.right) if i == l - 1: out.append(node.val) q = q[l:] return out
# DFS递归遍历 # 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 classSolution: defrightSideView(self, root: Optional[TreeNode]) -> List[int]: out = []
//递归法,在遍历的过程中,先访问右子树,确保右侧的节点先被处理,然后再访问左子树。这样就能保证每层最右侧的节点被加入到结果列表中。 /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ funcrightSideView(root *TreeNode) (out []int) { if root == nil { return out }
var dfs func(node *TreeNode, level int) dfs = func(node *TreeNode, level int) { if node == nil { return }
// 每层只保留最右边的节点值 if level == len(out) { out = append(out, node.Val) }
# DFS # 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 classSolution: defaverageOfLevels(self, root: Optional[TreeNode]) -> List[float]: result = []
//DFS /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ funcaverageOfLevels(root *TreeNode) []float64 { var result []float64
var dfs func(node *TreeNode, level int) var sum []float64 var count []int
//DFS /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ type data struct{ sum, count int }