面试题 17.12. BiNode

68 阅读1分钟

二叉树数据结构TreeNode可用来表示单向链表(其中left置空,right为下一个链表节点)。实现一个方法,把二叉搜索树转换为单向链表,要求依然符合二叉搜索树的性质,转换操作应是原址的,也就是在原始的二叉搜索树上直接修改。返回转换后的单向链表的头节点。

注意: 本题相对原题稍作改动

示例:

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

题解:

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
// 方法一:迭代 二叉树中序遍历
var convertBiNode = function (root) {
    const stack = [];
    const head = new TreeNode(-1)
    let curr = head;
    while (stack.length || root != null) {
        if (root != null) {
            stack.push(root)
            root = root.left
        } else {
            root = stack.pop()
            curr.right = root;
            root.left = null;
            curr = root;
            root = root.right
        }
    }
    return head.right
};
// 方法二:递归 二叉树中序遍历
var convertBiNode = function (root) {
    const head = new TreeNode(-1)
    let curr = head;
    const order = (node) => {
        if (!node) return
        order(node.left)
        curr.right = node;
        node.left = null;
        curr = curr.righ;
        order(node.right)
    }
    order(root)
    return head.right
}

来源:力扣(LeetCode)

链接:leetcode.cn/problems/bi…

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。