LeetCode - Flatten Binary Tree to Linked List
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.
Solution:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public void flatten(TreeNode root) { 12 // Start typing your Java solution below 13 // DO NOT write main() function 14 //solve1(root); 15 if(root == null) return; 16 if(root.left != null){ 17 TreeNode left = root.left; 18 TreeNode right = root.right; 19 root.left = null; 20 root.right = left; 21 TreeNode rightMost = root.right; 22 while(rightMost.right != null){ 23 rightMost = rightMost.right; 24 } 25 rightMost.right = right; 26 } 27 flatten(root.right); 28 } 29 }

浙公网安备 33010602011771号