Title:
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
Test Instructions:
Given a binary tree, it turns itself into a single-linked list.
For example, given
1 / 2 5 /\ 3 4 6
transformed into a flat tree as shown:
1 2 3 4 5 6
Algorithm Analysis:
* This method directly on root node, first temporarily save the left and right subtree, if Root has a left dial hand tree, the root.right attached to the root.left,root.left to null, and then on the left subtree of the tree
* Find rightmost node and put the right subtree before it on the rightmost.right.
* Once done, the left subtree of root has been grafted between the right subtree and root, and the original left subtree becomes null and can be root.right recursively.
AC Code:
<span style= "Font-family:microsoft yahei;font-size:12px;" >/** * 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; if (root.left! = null) { TreeNode left = root.left; TreeNode right = Root.right; Root.left = null; Root.right = left; TreeNode rightmost = root.right; while (rightmost.right! = null) { rightmost = rightmost.right; } Rightmost.right = right; } Flatten (root.right); }} </span>
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode][java] Flatten Binary Tree to Linked List