Leetcode: Flatten Binary Tree to Linked List
来源:互联网 发布:c语言程序的基本单位 编辑:程序博客网 时间:2024/05/22 14:28
Question
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
click to show hints.
Solution
Analysis
Get idea from Code Ganker, hustyangiu的足迹.
When recursive function runs from top to down, it has linked the left child to root. The current root can be recorded by one global variable.
code
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ self.pre = None self.helper(root) def helper(self, root): if root==None: return right = root.right if self.pre!=None: self.pre.left = None self.pre.right = root self.pre = root self.helper(root.left ) self.helper(right)
Take home message
Get deeper understanding for currsive functions
def helper(self, root): A B C self.helper(root.left) self.helper(root.right)
The code above implements A, B and C while code runs from top to down.
def helper(self, root): self.helper(root.left) self.helper(root.right) A B C
The code above implements A, B and C while code runs from down to top.
For the recursive function, we can do anything from top to down or from down to top, or both of them. In general, we do things from down to top.
- LeetCode: Flatten Binary Tree to Linked List
- LeetCode Flatten Binary Tree to Linked List
- LeetCode: Flatten Binary Tree to Linked List
- [Leetcode] Flatten Binary Tree to Linked List
- [LeetCode] Flatten Binary Tree to Linked List
- Leetcode: Flatten Binary Tree to Linked List
- leetcode Flatten Binary Tree to Linked List
- LeetCode Flatten Binary Tree to Linked List
- LeetCode - Flatten Binary Tree to Linked List
- 【leetcode】Flatten Binary Tree to Linked List
- [LeetCode]Flatten Binary Tree to Linked List
- [Leetcode]Flatten Binary Tree to Linked List
- [leetcode]Flatten Binary Tree to Linked List
- LeetCode-Flatten Binary Tree to Linked List
- [leetcode] Flatten Binary Tree to Linked List
- LeetCode - Flatten Binary Tree to Linked List
- LeetCode:Flatten Binary Tree to Linked List
- [LeetCode] Flatten Binary Tree to Linked List
- 【小熊刷题】Validate Binary Search Tree <含recursion>
- 【cocos2d-x 3.7 飞机大战】 决战南海I (十一) 关于游戏场景
- 【cocos2d-x 3.7 飞机大战】 决战南海I (十二) 游戏结束场景
- 【cocos2d-x 3.7 飞机大战】 决战南海I (十三) 分数场景
- Leecode_Missing number
- Leetcode: Flatten Binary Tree to Linked List
- POJ 3645 解题报告
- 【LeetCode-面试算法经典-Java实现】【198-House Robber(抢劫犯)】
- Spring MVC MultiActionController example
- 【LeetCode-面试算法经典-Java实现】【199-Binary Tree Right Side View(从右边看二叉树)】
- Spring MVC MultiActionController annotation example
- 【LeetCode-面试算法经典-Java实现】【200-Number of Islands(岛的数目)】
- Spring MVC PropertiesMethodNameResolver example
- 正则表达式测试工具 regexbuddy