Flatten Binary Tree to Linked List

题目

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

For example,
Given

         1
        / \
       2   5
      / \   \
     3   4   6

The flattened tree should look like:

   1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6

思路分析

这道题的经典实现方式是用recursive post order traverse(right,left,root)来实现

class Solution {
    private TreeNode prev = null;
    public void flatten(TreeNode root) {
        if(root == null) return;
        flatten(root.right);   <<<< first flat the right nodes
        flatten(root.left);    <<<< Then flat the left nodes
        root.right = prev;     <<<< assign the previous root to new right node
        root.left = null;
        prev = root;
    }
}

results matching ""

    No results matching ""