LeetCode114 Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

将二叉树变成扁平的,类似于LinkedList的只有右子树的线性链表


基本思路:这不是前序遍历么,将节点存入list中,然后重新构建一个右子树。这就简单了。

 public void flatten(TreeNode root) {
        Stack<TreeNode> stack=new Stack<TreeNode>();
        List<TreeNode> list=new LinkedList<TreeNode>();
        TreeNode current=root;
        int i=0;
        while(!stack.isEmpty()||current!=null)//前序遍历节点存入list中
        {
            if(current!=null)
            {
                stack.push(current);
                list.add(current);
                current=current.left;
            }else
            {
                current=stack.pop();
                current=current.right;
            }
        }
        current=root;//将list中的节点重新构建右子树,注意之前的链接还在,所以构建的时候,要将左孩子清空。
        i=1;
        while(i<list.size())
        {
            current.left=null;
            current.right=list.get(i);
            current=current.right;
            i++;
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值