【LeetCode】Flatten Binary Tree to Linked List

Flatten Binary Tree to Linked List 
Total Accepted: 9501 Total Submissions: 35694 My Submissions
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
【LeetCode】Flatten Binary Tree to Linked List_第1张图片

The flattened tree should look like:

【LeetCode】Flatten Binary Tree to Linked List_第2张图片

其实就是将前序遍历转为链表。
有两种处理办法
1)、将前序遍历组成集合,然后再重新建立链表。我个人也比较习惯这种处理,很方便。
2)、在前序遍历的过程中,组装链表。
Java AC 1

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void flatten(TreeNode root) {
        if(root == null){
            return;
        }
        List<Integer> list = new ArrayList<Integer>();
        preOrder(list,root);
        int size = list.size();
        TreeNode point = root;
        for(int i = 1; i < size; i++){
            point.right = new TreeNode(list.get(i));
            point.left = null;
            point = point.right;
        }
    }
    public void preOrder(List<Integer> list, TreeNode root){
        if(root == null){
            return;
        }
        list.add(root.val);
        if(root.left != null){
            preOrder(list,root.left);
        }
        if(root.right != null){
            preOrder(list,root.right);
        }
    }
}
Java AC 2

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void flatten(TreeNode root) {
        if(root == null){
            return;
        }
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        TreeNode lastNode = null;
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            if(lastNode != null){
                lastNode.left = null;
                lastNode.right = node;
            }
            lastNode = node;  
            TreeNode left = node.left;  
            TreeNode right = node.right;  
            if (right != null) {  
                stack.push(right);  
            }  
            if (left != null) {  
                stack.push(left);  
            }
        }
    }
}

你可能感兴趣的:(【LeetCode】Flatten Binary Tree to Linked List)