欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-21 19:18:06
...

题目链接:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/

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

思路:先序遍历用list存储,再连接。

AC 1ms 99.6% Java:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List<TreeNode> list=new ArrayList();
    public void flatten(TreeNode root) {
        if(root==null)
            return;
        helper(root);
        TreeNode dummy=new TreeNode(0);
        TreeNode p=dummy;
        for(int i=0;i<list.size();i++){
            p.left=null;
            p.right=list.get(i);
            p=p.right;
        }
        root=dummy.right;
    }
    public void helper(TreeNode root){
        if(root==null)
            return;
        list.add(root);
        helper(root.left);
        helper(root.right);
    }
}