LeetCode之flatten binary tree
来源:互联网 发布:电脑突然连接不上网络 编辑:程序博客网 时间:2024/06/05 17:26
问题描述:
/** * 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 */
把一个二叉树flatten 成一个像链表一样的树,如上图所示。
可以看出,结果树就是二叉树前序遍历的结果顺序。
所以,可以先把二叉树前序遍历一下,把遍历的结果存储到队列queue当中,再构建新的结果二叉树即可。
代码如下:
public void flatten(TreeNode root) { if (root == null) return; Stack<TreeNode> stack = new Stack<TreeNode>(); Queue<TreeNode> queue = new LinkedList<TreeNode>(); stack.push(root); queue.add(root); while (!stack.isEmpty()) { TreeNode top = stack.peek(); if (top.left != null) { queue.add(top.left); stack.push(top.left); top.left = null; } else if (top.right != null) { queue.add(top.right); stack.push(top.right); top.right = null; } else { //top.left == null && top.right == null stack.pop(); } } TreeNode node = queue.poll(); while (!queue.isEmpty()) { node.right = queue.poll(); node = node.right; } }
上面这种方法借用了队列queue和栈stack。下面这种方法也很巧妙:
public void flatten(TreeNode root) { if (root == null) return; if (root.left != null) { TreeNode rightMost = findRightMost(root.left); TreeNode rightChild = root.right; root.right = root.left; root.left = null; rightMost.right = rightChild; } flatten(root.right); } private TreeNode findRightMost(TreeNode root) { if (root == null || root.right == null) return root; return findRightMost(root.right); }
0 0
- LeetCode之flatten binary tree
- 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
- 对于Toast的使用
- jquery常用表单&DOM操作方法
- Swift 版本相册,防微信相册
- 对 AFNetworking 二次封装应用 - POST
- 源码-PL/SQL从入门到精通-第十七章-面向对象编程-Part 1
- LeetCode之flatten binary tree
- String类
- 混淆实战
- android studio tabhost基础 多功能时钟app 闹钟执行后清除 alarmmanager(六)
- 杭电5753之Permutation Bo
- hdu 5753 Permutation Bo (水题)
- redis应用的总结
- LINUX多线程读写同一个文件 加锁
- windows下theano开发环境搭建(实现了GPU加速)