First, the topic
1, examining
2. Analysis
A binary tree is given, which is a diagonal right binary tree in order to traverse the sequence.
Second, the answer
1, Ideas:
Method One,
A stack is used for the first order traversal, and the nodes are reassembled when traversing.
Public voidFlatten (TreeNode root) {Stack<TreeNode> stack =NewStack<treenode>(); if(Root = =NULL) return; Stack.add (root); TreeNode Tmpnode=Root; while(!Stack.isempty ()) {TreeNode node=Stack.pop (); if(Node.right! =NULL) Stack.add (node.right); if(Node.left! =NULL) Stack.add (node.left); if(Node! =root) {Tmpnode.right=node; Tmpnode.left=NULL; Tmpnode=node; } } }
Method Two,
Using recursion
The recursive implementation of right-to-left and root traversal, and stitching the original binary tree node order.
Private NULL ; Public void Flatten (TreeNode root) { ifnull) return; Flatten (root.right); Flatten (root.left); = prev; NULL ; = root; }
Method Three,
Using Morris Traversal method clue two fork tree.
Clue two fork tree, which uses the free pointer in the leaf node to point to the subsequent node in the middle order traversal.
Good performance, O (1) Space complexity
Public voidFlatten3 (TreeNode root) {TreeNode cur=Root; TreeNode Pre=Root; while(cur! =NULL) { if(Cur.left = =NULL) {cur=Cur.right; } Else{Pre=Cur.left; while(Pre.right! =NULL&& Pre.right! =cur) Pre=Pre.right; if(Pre.right = =NULL) {Pre.right=cur; Cur=Cur.left; } Else{TreeNode right=Cur.right; Cur.right=Cur.left; Cur.left=NULL; Pre.right=Right ; Cur=Right ; } } } }
Flatten Binary Tree to Linked List