Flatten Binary Tree to Linked List

Posted codingEskimo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

Flatten Binary Tree to Linked List

Jan 29 - Flatten Binary Tree To Linked List; DFS;

114. Flatten Binary Tree to Linked List

114. Flatten Binary Tree to Linked List

Flatten Binary Tree to Linked List

114. Flatten Binary Tree to Linked List