leetcode Flatten Binary Tree to Linked List题解

博客围绕将二叉树转换为深度遍历的只有右子树节点的二叉树展开。先给出题目描述,接着进行中文理解说明,阐述解题思路为深度遍历二叉树得到序列并修改指针,最后给出了Java代码实现。

摘要生成于 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

中文理解:

给定一个二叉树,将二叉树转换为深度遍历的只有右子树节点的二叉树。

解题思路:

深度遍历二叉树,得到深度遍历序列,然后该表该序列的指针。

代码(java):

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        if(root==null)return;
        ArrayList <TreeNode> nodes=new ArrayList();
        Stack<TreeNode> stack=new Stack<TreeNode>();
        stack.push(root);
        TreeNode temp=null;
        while(!stack.isEmpty()){
            temp=stack.pop();
            nodes.add(temp);
            if(temp.right!=null)stack.push(temp.right);
            if(temp.left!=null)stack.push(temp.left);
        }
        for(int i=0;i<nodes.size()-1;i++){
            nodes.get(i).left=null;
            nodes.get(i).right=nodes.get(i+1);
        }
        nodes.get(nodes.size()-1).left=null;
        nodes.get(nodes.size()-1).right=null;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值