114. 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
---
/** * 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; TreeNode left = root.left; TreeNode right = root.right; if(left!=null){ // put to right root.right = left; root.left = null; TreeNode rightmost = left; while(rightmost.right != null){ rightmost = rightmost.right; } rightmost.right = right; // point the right most to the original right child } flatten(root.right); } }
浙公网安备 33010602011771号