Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place.
For example,
Given1 / 2 5 / 3 4 6The flattened tree should look like:
1 2 3 4 5 6
算法思想:很明显的先序遍历。
思路:维护一个尾节点,每次递归时候,将root节点插到尾节点的右子树上,将左子树置为空,为了防止断链,要将左右子树记录下来。
代码如下:
1 public class Solution { 2 TreeNode tail = new TreeNode(0); 3 public void flatten(TreeNode root){ 4 if(root == null) return; 5 tail.right = root; 6 tail.left = null; 7 tail = tail.right; 8 TreeNode left = root.left; 9 TreeNode right = root.right; 10 if(root.left != null) flatten(left); 11 if(root.right != null) flatten(right); 12 } 13 }