589. N-ary Tree Preorder Traversal
Given an n-ary tree, return the preorder traversal of its nodes' values.
For example, given a 3-ary
tree:
Return its preorder traversal as: [1,3,5,6,2,4]
.
给定一个 N 叉树,返回其节点值的前序遍历。
思路:前序遍历,即首先把根节点的值放到list中,然后再遍历其子节点们的值,同时对于每一个子节点也做同样的操作。
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
res=[]
if root is None:
return res
res.append(root.val)
for child in root.children:
res.extend(self.preorder(child))
return res
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]
.
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
res=[]
if root is None:
return res
for child in root.children:
res.extend(self.postorder(child))
res.append(root.val)
return res
617. Merge Two Binary Trees
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
Example 1:
Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 Output: Merged tree: 3 / \ 4 5 / \ \ 5 4 7
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if t1 is None and t2 is None:
return
if t1 is None:
return t2
if t2 is None:
return t1
t1.val+=t2.val
t1.right=self.mergeTrees(t1.right,t2.right)
t1.left=self.mergeTrees(t1.left,t2.left)
return t1