例如,给定二叉树
1 / 2 5 / \ 3 4 6
将其展开为:
1 2 3 4 5 6
python:(官方解法:前序遍历)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def flatten(self, root): """ :type root: TreeNode :rtype: None Do not return anything, modify root in-place instead. """ preordList = list() def preorderTraversal(root): if root: preordList.append(root) preorderTraversal(root.left) preorderTraversal(root.right) preorderTraversal(root) size = len(preordList) for i in range(1,size): prev,curr = preordList[i-1],preordList[i] prev.left = None prev.right = curr
go:
func flatten(root *TreeNode) { list := preorderTraversal(root) for i := 1; i < len(list); i++ { prev, curr := list[i-1], list[i] prev.Left, prev.Right = nil, curr } } func preorderTraversal(root *TreeNode) []*TreeNode { list := []*TreeNode{} if root != nil { list = append(list, root) list = append(list, preorderTraversal(root.Left)...) list = append(list, preorderTraversal(root.Right)...) } return list }
原文:https://www.cnblogs.com/ghl666/p/13423702.html