leetcode114. Flatten Binary Tree to Linked List

本文介绍了一种将二叉树结构展平为链表的方法,通过两种不同的算法实现:一种是利用栈进行前序非递归遍历;另一种是采用后序遍历策略,先遍历右节点再遍历左节点。这两种方法均能有效地改变二叉树的结构,使其呈现出链表形式。

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

114. 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

解法

前序非递归遍历。对每个结点的右结点取栈顶元素,左结点致空null。

 public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }

        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);

        while (!stack.empty()) {
            TreeNode curr = stack.pop();
            if (curr.right != null) {
                stack.push(curr.right);
            }
            if (curr.left != null) {
                stack.push(curr.left);
            }
            if (!stack.empty()) {
                curr.right = stack.peek();
            }
            curr.left = null;
        }
    }

解法二

后序遍历,但是先遍历右边的结点,右左根。使得遍历的每个结点的右结点为前一个遍历到的结点,左结点为空。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值