leetcode 114. Flatten Binary Tree to Linked List (Python版)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 114. Flatten Binary Tree to Linked List (Python版)相关的知识,希望对你有一定的参考价值。
题目:
Given a binary tree, flatten it to a linked list in-place.
算法思路:
其实该题目就是二叉树前序遍历的变形
我代码沿用leetcode 144. Binary Tree Preorder Traversal
代码:
class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ if root == None:return [] stack = [root] result = [] while len(stack) != 0: tmp_root = stack.pop() if tmp_root == None:continue result.append(tmp_root) stack.append(tmp_root.right) stack.append(tmp_root.left) return result def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ result = self.preorderTraversal(root) for i in range(1,len(result)): result[i-1].left = None result[i-1].right = result[i]
以上是关于leetcode 114. Flatten Binary Tree to Linked List (Python版)的主要内容,如果未能解决你的问题,请参考以下文章
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