Leetcode 114 Flatten Binary Tree to Linked List
Posted yuyinzi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 114 Flatten Binary Tree to Linked List相关的知识,希望对你有一定的参考价值。
题目介绍
给定二叉树,将其原地变成一个链表。
Example
:
1
/ 2 5
/ 3 4 6
1
2
3
4
5
6
Solutions
直观解法
发现链表的结果与先序遍历一致,因此先进行先序遍历,再根据遍历的结果构造链表。
# 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 flatten(self, root):
"""
:type root: TreeNode
:rtype: None Do not return anything, modify root in-place instead.
"""
res = []
def helpfunc(root):
if not root:
return
res.append(root)
helpfunc(root.left)
helpfunc(root.right)
helpfunc(root)
for i in range(1, len(res)):
res[i-1].right = res[i]
res[i-1].left = None
逆序遍历
逆序遍历即按照[右子树,左子树,根]的方式来遍历,所以遍历结果为6->5->4->3->2->1
,将遍历结果逐一进行类似于链表反转的操作:
class Solution(object):
def __init__(self):
self.prev = None
def flatten(self, root):
"""
:type root: TreeNode
:rtype: None Do not return anything, modify root in-place instead.
"""
if not root:
return
self.flatten(root.right)
self.flatten(root.left)
root.right = self.prev
root.left = None
self.prev = root
非递归解法
利用栈,先存右子树再存左子树,其实也是前序遍历的非递归写法。
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: None Do not return anything, modify root in-place instead.
"""
stack = []
if root:
stack.append(root)
while stack:
node = stack.pop()
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
if stack:
node.right = stack[-1]
node.left = None
以上是关于Leetcode 114 Flatten Binary Tree to Linked List的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 114. Flatten Binary Tree to Linked List
leetcode--114. Flatten Binary Tree to Linked List
LeetCode 114. Flatten Binary Tree to Linked List
Leetcode 114, Flatten Binary Tree to Linked List