首页 > 代码库 > Flatten Binary Tree to Linked List

Flatten Binary Tree to Linked List

Note:

It is easier to use divided conquer. As you can see, the question is just to add right to left‘s last. Here we care more about last then the top because top can always be traced by root. Since the right is the last if it is null, first return right and then check left side. 

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: a TreeNode, the root of the binary tree
     * @return: nothing
     */
    public void flatten(TreeNode root) {
        // write your code here
        flattenTree(root);
    }
    
    private TreeNode flattenTree(TreeNode root) {
        if (root == null) {
            return root;
        }
        
        //This problem is looking for the last element
        TreeNode leftLast = flattenTree(root.left);
        TreeNode rightLast = flattenTree(root.right);
        
        if (leftLast != null) {
            leftLast.right = root.right;
            root.right = root.left;
            root.left = null;
        }
        
        if (rightLast != null) {
            return rightLast;
        }
        
        if (leftLast != null) {
            return leftLast;
        }
        
        return root;
    }
}

 

// The traverse version. Please check http://www.jiuzhang.com/solutions/flatten-binary-tree-to-linked-list/

Flatten Binary Tree to Linked List