【Java】【LeetCode】114. Flatten Binary Tree to Linked List

本文介绍了一种将二叉树原地转换为链表的方法。通过遍历二叉树,将左子树连接到当前节点的右子树,再将左子树置空,最后利用栈处理无左子树的情况,实现了树的扁平化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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

对整棵树一直向右子树方向遍历。当遍历的节点有右孩子时,就将其入栈。有左孩子时,将其更新为当前节点的右孩子,左孩子置空。当左孩子为空时而栈不空时,就弹出栈,作为右孩子。

代码如下:

public class FlattenBinaryTreetoLinkedList {

    public static void main(String[] args) {
        /**
         * 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
         */
        TreeNode root = new TreeNode(1);
        TreeNode tn2 = new TreeNode(2);
        TreeNode tn3 = new TreeNode(3);
        TreeNode tn4 = new TreeNode(4);
        TreeNode tn5 = new TreeNode(5);
        TreeNode tn6 = new TreeNode(6);
        root.left = tn2;
        root.right = tn5;
        tn2.left = tn3;
        tn2.right = tn4;
        tn5.right = tn6;
        flatten(root);
        while (root != null) {
            System.out.println(root.val);
            if (root.left != null) {
                System.out.println("Error");
                break;
            }
            root = root.right;
        }
    }

    public static void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode tn = root;
        while (tn != null) {
            if (tn.right != null) {
                stack.push(tn.right);
            }
            if (tn.left != null) {
                tn.right = tn.left;
                tn.left = null;
            } else {
                if (!stack.isEmpty()) {
                    tn.right = stack.pop();
                }
            }
            tn = tn.right;
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值