首页 > 其他 > 详细

二叉树展开为链表

时间:2020-08-02 18:14:08      阅读:83      评论:0      收藏:0      [点我收藏+]

技术分享图片

前序遍历+重赋值

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    List<Integer> list = new ArrayList<>();
    public void flatten(TreeNode root) {
        if(root == null) return ;
        preOrder(root);
        int i = 0;
        while(i +1 < list.size()){
            root.left = null;
            root.right = new TreeNode(list.get(i+1));
            root = root.right;   
            i++;          
        }

    }
    public void preOrder(TreeNode root){
        if(root == null) return ;
        list.add(root.val);
        preOrder(root.left);
        preOrder(root.right);
    }
    
}

技术分享图片

二叉树展开为链表

原文:https://www.cnblogs.com/cstdio1/p/13419748.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!