114-Flatten Binary Tree to Linked List

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;
    }
}

你可能感兴趣的:(算法与数据结构,leetcode全解)