[LeetCode] Flatten Binary Tree to Linked List
2014-04-22 17:41
351 查看
Total Accepted: 10982Total Submissions:40794My
Submissions
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
The flattened tree should look like:
Submissions
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
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public void flatten(TreeNode root) { if (root == null) return; flatten(root.left); flatten(root.right); TreeNode node = root.left; if (root.left != null) { // get last node in left tree while (node.right != null) node = node.right; node.right = root.right; root.right = root.left; root.left = null; } } }
public class Solution { // store current last node private TreeNode last; public void flatten(TreeNode root) { if (root == null) return; TreeNode tmp = root.right; if (last == null) last = root; else { last.right = root; last = root; } flatten(root.left); flatten(tmp); root.left = null; } }
// without recursion public class Solution { // store current last node public void flatten(TreeNode root) { while (root != null) { if (root.left != null) { // get bigest element in left tree TreeNode p = root.left; while (p.right != null) p = p.right; p.right = root.right; root.right = root.left; root.left = null; } root = root.right; } } }
相关文章推荐
- Leetcode: Flatten Binary Tree to Linked List
- LeetCode | Flatten Binary Tree to Linked List(二叉树转化成链表)
- [Leetcode]Flatten Binary Tree to Linked List (三种方法)
- leetcode——114—— Flatten Binary Tree to Linked List
- [Leetcode][JAVA] Flatten Binary Tree to Linked List
- leetcode Flatten Binary Tree to Linked List
- Leetcode[114]-Flatten Binary Tree to Linked List
- 【Leetcode】Flatten Binary Tree to Linked List (other)
- Flatten Binary Tree to Linked List (二叉树转前序链表)【leetcode】
- Leetcode Flatten Binary Tree to Linked List
- LeetCode: Flatten Binary Tree to Linked List
- Flatten Binary Tree to Linked List -- LeetCode
- 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
- LeetCode114—Flatten Binary Tree to Linked List
- leetcode Flatten Binary Tree to Linked List