原题链接在这里:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/
题目:
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 a Multilevel Doubly Linked List.
root.left == null时, 直接跳到root.right进行下一步.
root.left!=null 时, 目标就是把roo.left 这个子树的右边一条插进root 和 root.right之间.
Time Complexity: O(n).
Space: O(1).
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public void flatten(TreeNode root) { 12 TreeNode cur = root; 13 while(cur != null){ 14 if(cur.left == null){ 15 cur = cur.right; 16 continue; 17 } 18 19 TreeNode left = cur.left; 20 while(left.right != null){ 21 left = left.right; 22 } 23 24 left.right = cur.right; 25 cur.right = cur.left; 26 cur.left = null; 27 cur = cur.right; 28 } 29 } 30 }