二叉树这一数据结构十分重要,在此不断补充一些有趣味的题目,不断学习。
623. Add One Row to Tree
Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1.
The adding rule is: given a positive integer depth d, for each NOT null tree nodes N in depth d-1, create two tree nodes with value v as N's left subtree root and right subtree root. And N's original left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root. If depth d is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root's left subtree.
题目解析:
插入一层,明显拷问的是层次遍历的知识。只需要对d=1时特殊处理,queue中存放插入结点的上一层,然后逐个插入,并把原子节点连上。
class Solution:
def addOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode:
if d == 1:
p = TreeNode(v)
p.left = root
return p
queue = [root]
depth = 1
while queue:
depth += 1
if depth == d:
break
level = []
for node in queue:
if node.left:
level.append(node.left)
if node.right:
level.append(node.right)
queue = level
for x in queue:
lt = x.left
rt = x.right
x.left = TreeNode(v)
x.left.left = lt
x.right = TreeNode(v)
x.right.right = rt
return root
实际应用及遇到的题目都是二叉树较多,LeetCode中集中了几道n叉树的题目,在此简要看一下,树这一结构的一般解题思路。
590. N-ary Tree Postorder Traversal
Given an n-ary tree, return the postorder traversal of its nodes' values.
For example, given a 3-ary
tree:
Return its postorder traversal as: [5,6,3,2,4,1]
.
题目解析:
先回忆一下二叉树的后序遍历思路,由于后进先出,在children压入栈的时候,要先逆转;另外,记录前一个结点,用于判断当前结点的子树是否已遍历的。
class Solution:
def postorder(self, root: 'Node') -> List[int]:
if not root:
return []
stack = [root]
res = []
pre = None
while stack:
node = stack[-1]
if node.children and pre != node.children[-1]: # 已访问过的chiled 处理
stack.extend(node.children[::-1])
else:
node = stack.pop()
res.append(node.val)
pre = node
return res
429. N-ary Tree Level Order Traversal
Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
题目解析:
n叉树的层次遍历如出一辙。
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
res = []
if not root:
return res
queue = [root]
while queue:
vals = []
level = []
for node in queue:
vals.append(node.val)
level.extend(node.children)
res.append(vals)
queue = level
return res