剑指 Offer II 052. 展平二叉搜索树

67 阅读1分钟

给你一棵二叉搜索树,请 按中序遍历 将其重新排列为一棵递增顺序搜索树,使树中最左边的节点成为树的根节点,并且每个节点没有左子节点,只有一个右子节点。

示例 1:

image.png

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

示例 2:

image.png

输入: root = [5,1,7]
输出: [1,null,5,null,7]

题解:

/**
 * 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 {TreeNode}
 */
//  方法一:
var increasingBST = function (root) {
    const res = []
    // 迭代的方式获取中序遍历结果
    if (root != null) {
        const stack = []
        while (stack.length || root != null) {
            if (root != null) {
                stack.push(root)
                root = root.left
            } else {
                root = stack.pop();
                res.push(root.val)
                root = root.right
            }
        }
    }
    // 生成只有右树的结构
    const newNode = new TreeNode()
    let curNode = newNode
    for(let ca of res){
        curNode.right = new TreeNode(ca)
        curNode = curNode.right
    }
    return newNode.right
};
// 方法二:
var increasingBST = function (root) {
    const newNode = new TreeNode()
    let curNode = newNode
    if (root != null) {
        const stack = []
        while (stack.length || root != null) {
            if (root != null) {
                stack.push(root)
                root = root.left
            } else {
                root = stack.pop();
                // 第一次进入这里的时候,node是整个树当中最左边最小的节点
                curNode.right = root;
                // 上面只是curNode的右节点指向了当前节点,为避免链串
                root.left = null
                // 相当于向前走了一步(返回的链表只有右节点,向右走了一步,方便下次指向)
                curNode = root
                root = root.right
            }
        }
    }
    return newNode.right
}

来源:力扣(LeetCode)

链接:leetcode.cn/problems/NY…

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