LeetCode Flatten Binary Tree to Linked List
2016-03-04 09:26
309 查看
LeetCode解题之Flatten Binary Tree to Linked List
原题
把一棵二叉树变为链表,也就是一棵所有节点要么没有子节点,要么只有右节点的二叉树。注意点:
无
例子:
输入:
[code] 1 / \ 2 5 / \ \ 3 4 6
输出:
[code] 1 \ 2 \ 3 \ 4 \ 5 \ 6
解题思路
可以看出来变化后每个节点其实都是指向了在先序遍历中的后一个节点。所以就通过栈的方式来先序遍历原树,如果一个节点有左节点,那么把它的右节点压栈(如果有的话),右指针指向原来的左节点;如果一个节点没有子节点,应该把它的右指针指向栈顶的节点。AC源码
[code]# 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. """ stack = [] while root: if root.left: if root.right: stack.append(root.right) root.right, root.left = root.left, None if not root.right and stack: root.right = stack.pop() root = root.right if __name__ == "__main__": None
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
相关文章推荐
- Centos6.5 64+oracle11.2.0.4+rman 搭建物理DG
- 伸展树
- 内存管理与垃圾回收2之内存溢出的三种情况及解决办法
- 信号(待填)
- No space left on device
- 通俗解释遗传算法及其Matlab实现
- 三月
- 软件测试(一)我的一次DEBUG
- eclipse 出包 is not a sibling in the same 问题修复
- 算法-hilo算法
- Treap树
- 早晨突然想到的几句话
- 简明 Vim 练级攻略
- 结构体定义别名时定义为*~~的情况
- python-技巧
- Android启动活动的最佳写法
- Android keystore 密码忘记了的找回办法
- .NET面试题解析(03)-string与字符串操作
- oracle 两个日期相差得月数
- 输入格式CombineFileInput