[LeetCode]题解(python):114 Flatten Binary Tree to Linked List

题目来源


https://leetcode.com/problems/flatten-binary-tree-to-linked-list/

Given a binary tree, flatten it to a linked list in-place.


题意分析


Input: binary tree

Output: flattened tree

Conditions:将一个二叉树压平为一个flatten 树,也就是一条斜线


题目思路


先将左右子树压平,然后将左子树嵌入到本节点与右子树之间。


AC代码(Python)

 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution(object):
 9     def flatten(self, root):
10         """
11         :type root: TreeNode
12         :rtype: void Do not return anything, modify root in-place instead.
13         """
14         if root == None:
15             return
16         self.flatten(root.left)
17         self.flatten(root.right)
18         p = root
19         if p.left == None:
20             return
21         p = p.left
22         while p.right:
23             p = p.right
24         p.right = root.right
25         root.right = root.left
26         root.left = None
27         
原文地址:https://www.cnblogs.com/loadofleaf/p/5523877.html