Flatten a binary tree to a fake "linked list" in pre-order traversal.
Here we use the right pointer in TreeNode as the nextpointer in ListNode.
Example
1 1 2 / \ 2 5 => 3 / \ \ 3 4 6 4 5 6
Note
Don ' t forget to mark the left child of each node to null. Or you'll get time limit exceeded or Memory Limit exceeded.
Challenge
Do it in-place without any extra memory.
Recursively, note if the left dial hand tree is null directly flatten the right subtree and then returns, otherwise times out
/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/ Public classSolution {/** * @paramroot:a TreeNode, the root of the binary tree *@return: Nothing*/ Public voidFlatten (TreeNode root) {//Write your code here if(Root = =NULL) return; if(Root.left = =NULL&& Root.right = =NULL) return; if(Root.left! =NULL) {flatten (root.left); } if(Root.right! =NULL) {flatten (root.right); } TreeNode Temp=Root.right; if(Root.left! =NULL) {Root.right=Root.left; Root.left=NULL; TreeNode P=Root; while(P.right! =NULL) P=P.right; P.right=temp; } return; }}
Lintcode-easy-flatten Binary Tree to Linked List