leetcode114.二叉树展开为链表

leetcode114.二叉树展开为链表

题目

给你二叉树的根结点 root ,请你将它展开为一个单链表:

展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。
展开后的单链表应该与二叉树 先序遍历 顺序相同。

用例

输入:root = [1,2,5,3,4,null,6]
输出:[1,null,2,null,3,null,4,null,5,null,6]
输入:root = []
输出:[]
输入:root = [0]
输出:[0]

求解

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {void} Do not return anything, modify root in-place instead.
 */
var flatten = function(root) {
    return changeTree(root)
    //递归转换
    function changeTree(root){
        if(root==null){
            return
        }
        //右子树接到左子树最后节点的右节点上
        let p = find_mid_last(root.left)
        if(p){
            p.right = root.right
            root.right = null
            root.right = root.left
            root.left = null
        }
        changeTree(root.right)
    }
    //寻找最后的那个节点
    function find_mid_last(root){
        if(root==null){
            return
        }
        while(root.left!=null||root.right!=null){
            if(root.right!=null){
                root=root.right
            }else{
                root=root.left
            }
        }
        return root
    }
};
posted @ 2021-11-23 15:09  BONiii  阅读(35)  评论(0)    收藏  举报