[LC] 114. Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

    1
   / 
  2   5
 /    
3   4   6

The flattened tree should look like:

1
 
  2
   
    3
     
      4
       
        5
         
          6

Solution 1:
 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution(object):
 9     def flatten(self, root):
10         """
11         :type root: TreeNode
12         :rtype: None Do not return anything, modify root in-place instead.
13         """
14         self.prev = None
15         def dfs(root):
16             if root is None:
17                 return None
18             # reverse preOrder traveral
19             # use pre_node to track the previous node to connect as current right
20             dfs(root.right)
21             dfs(root.left)
22             root.right = self.prev
23             root.left = None
24             self.prev = root
25         dfs(root)

Solution 2:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        helper(root);
    }
    
    private TreeNode helper(TreeNode root) {
        if (root == null) {
            return null;
        }
        
        TreeNode lastLeft = helper(root.left);
        TreeNode lastRight = helper(root.right);
        if (lastLeft != null) {
            lastLeft.right = root.right;
            root.right = root.left;
            root.left = null;
        }
        if (lastRight != null) {
            return lastRight;
        }
        if (lastLeft != null) {
            return lastLeft;
        }
        return root;
    }
}

Solution 3:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        LinkedList<TreeNode> stack = new LinkedList<>();
        stack.offerFirst(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.pollFirst();
            if (cur.right != null) {
                stack.offerFirst(cur.right);
            }
            if (cur.left != null) {
                stack.offerFirst(cur.left);
            }
            if (!stack.isEmpty()) {
                cur.right = stack.peekFirst();
            }
            cur.left = null;
        }
    }
}
原文地址:https://www.cnblogs.com/xuanlu/p/11725036.html