leetcode--114. Flatten Binary Tree to Linked List
阿新 • • 發佈:2017-09-02
turn spa preorder 先序 reorder 復雜 treenode 時間 lin
1、問題描述
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
Hints:
If you notice carefully in the flattened tree, each node‘s right child points to the next node of a pre-order traversal.
2、邊界條件:無
3、思路:從示例可以看出,變成list之後是原來的先序遍歷結果。那麽就采用先序遍歷把treenode轉為list,再轉為樹。
4、代碼實現
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public void flatten(TreeNode root) { List<TreeNode> result = new ArrayList<>(); preOrder(result, root); TreeNode dummy = new TreeNode(0); dummy.right = root; TreeNode newTree = dummy; for (int i = 0; i < result.size(); i++) { newTree.right = result.get(i); newTree.left= null; newTree = newTree.right; } root = dummy.right; } public void preOrder(List<TreeNode> result, TreeNode root) { if (root == null) { return; } result.add(root); preOrder(result, root.left); preOrder(result, root.right); } }
方法二
My short post order traversal Java solution for share private TreeNode prev = null; public void flatten(TreeNode root) { if (root == null) return; flatten(root.right);//先把右子樹flatten,prev=root.right flatten(root.left);//再把左子樹flatten root.right = prev;//左子樹的最右邊是首先flatten的,所以就掛接了prev=root.right root.left = null; prev = root; }
5、時間復雜度:O(N),空間復雜度:O(N)
6、api
leetcode--114. Flatten Binary Tree to Linked List