114-Flatten Binary Tree to Linked List

kevin聰發表於2018-05-25

Description

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

問題描述

給定二叉樹, 原位將它壓縮為連結串列


問題分析
後序遍歷, 先處理右子樹後處理左子樹, 注意將左子樹設定為null


解法

class Solution {
    public void flatten(TreeNode root){
        flatten(root, null);
    }
    private TreeNode flatten(TreeNode root, TreeNode pre) {
        if(root == null) return pre;
        //注意這裡pre的變化
        pre = flatten(root.right, pre);    
        pre = flatten(root.left, pre);
        root.right = pre;
        //注意這裡
        root.left = null;
        pre = root;

        return pre;
    }
}

相關文章