给你一棵二叉搜索树的 root ,请你 按中序遍历 将其重新排列为一棵递增顺序搜索树,使树中最左边的节点成为树的根节点,并且每个节点没有左子节点,只有一个右子节点。
示例 1:
输入: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:
输入: 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 = []
// 获取中序遍历结果 => 左头右
inorder(root, res)
const rootNode = new TreeNode(-1)
let currNode = rootNode
// 遍历生成新的结构
for (let val of res) {
currNode.right = new TreeNode(val)
currNode = currNode.right
}
return rootNode.right
};
const inorder = (root, res) => {
// 中序遍历方法一:递归
// if (root == null) return
// inorder(root.left, res)
// res.push(root.val)
// inorder(root.right, res)
// 中序遍历方法二:迭代
const stack = []
while (stack.length || root) {
if (root != null) {
stack.push(root)
root = root.left;
} else {
root = stack.pop();
res.push(root.val)
root = root.right;
}
}
}
// 方法二:中序遍历时直接获取新的数据结构修改指针方向
var increasingBST = function (root) {
const stack = []
let nodeRoot = new TreeNode(-1)
let currNode = nodeRoot
while (stack.length || root) {
if (root != null) {
stack.push(root)
root = root.left;
} else {
root = stack.pop();
// 方法一:
currNode.right = new TreeNode(root.val)
currNode = currNode.right
// // 方法二:
// currNode.right = root
// root.left = null
// currNode = root
root = root.right;
}
}
return nodeRoot.right
}
来源:力扣(LeetCode)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。