LeetCode 114. 二叉树展开为链表(Flatten Binary Tree to Linked List)

114. 二叉树展开为链表
114. Flatten Binary Tree to Linked List

题目描述
Given a binary tree, flatten it to a linked list in-place.
给定一个二叉树,原地将它展开为链表。

LeetCode114. Flatten Binary Tree to Linked List

For example, given the following tree:

    1
   / 
  2   5
 /    
3   4   6

The flattened tree should look like:

1
 
  2
   
    3
     
      4
       
        5
         
          6

Java 实现
TreeNode Class

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

Iterative Solution

import java.util.Stack;

class Solution {
    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode curr = stack.pop();
            if (curr.right != null) {
                stack.push(curr.right);
            }
            if (curr.left != null) {
                stack.push(curr.left);
            }
            if (!stack.isEmpty()) {
                curr.right = stack.peek();
            }
            curr.left = null;  // don't forget this!
        }
    }
}

Recursive Solution

class Solution {
    private TreeNode prev = null;

    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        flatten(root.right);
        flatten(root.left);
        root.right = prev;
        root.left = null;
        prev = root;
    }
}

相似题目

参考资料

原文地址:https://www.cnblogs.com/hgnulb/p/10890933.html