题解 | 二叉搜索树与双向链表

二叉搜索树与双向链表

https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5

import java.util.*;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public TreeNode Convert(TreeNode pRootOfTree) {
        if (pRootOfTree == null) return null;
        TreeNode[] res = convert(pRootOfTree);
        return res[0];
    }

    public TreeNode[] convert(TreeNode root) {
        //TreeNode[0]是转换链表的最左侧节点
        //TreeNode[1]是转换链表的最右侧节点
        if (root.left == null && root.right == null) return new TreeNode[] {root, root};

        TreeNode[] leftRes = new TreeNode[2];
        TreeNode[] rightRes = new TreeNode[2];
        TreeNode[] curRes = new TreeNode[2];

        if (root.left != null) {
            leftRes = convert(root.left);
            //拼接
            leftRes[1].right = root;
            root.left = leftRes[1];
            curRes[0] = leftRes[0];
        } else {
            curRes[0] = root;
        }

        if (root.right != null) {
            rightRes = convert(root.right);
            //拼接
            rightRes[0].left = root;
            root.right = rightRes[0];
            curRes[1] = rightRes[1];
        } else {
            curRes[1] = root;
        }

        return curRes;
    }
}

全部评论

相关推荐

秋招投简历提醒助手:个人经验是,一般面二十场左右就会进入侃侃而谈阶段。我今年七月末的时候开始的第一次面试,都是很多不会,回复很慢。后面慢慢迭代,到九月中的时候基本上面啥说啥,很放松的状态
远程面试的尴尬瞬间
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务