题目链接
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
题目原文
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
The flattened tree should look like:
题目大意
将二叉树变成只有有节点的已排好序的树
解题思路
递归,如果有右子树,则将右子树作为该节点左子树的右子树
代码
# 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: void Do not return anything, modify root in-place instead.
"""
if root == None:
return
self.flatten(root.left)
self.flatten(root.right)
p = root
if p.left == None:
return
p = p.left
while p.right:
p = p.right
p.right = root.right
root.right = root.left
root.left = None