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

难度:medium

题目:给定二叉树,原地扁平化。

思路:后序遍历

Runtime: 6 ms, faster than 100.00% of Java online submissions for Flatten Binary Tree to Linked List.
Memory Usage: 40 MB, less than 100.00% of Java online submissions for Flatten Binary Tree to Linked List.

/**
 * 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) {
        rightFlatten(root);
    }
    
    private TreeNode rightFlatten(TreeNode root) {
        if (null == root) {
            return root;
        }
        TreeNode left = rightFlatten(root.left);
        TreeNode right = rightFlatten(root.right);
        if (left != null) {
            root.left = null;
            root.right = left;
            TreeNode rightMost = left;
            while (rightMost.right != null) {
                rightMost = rightMost.right;
            }
            rightMost.right = right;
        }
        
        return root;
    }
}

linm
1 声望4 粉丝

〜〜〜学习始于模仿,成长得于总结〜〜〜