(Java)leetcode-897 Increasing Order Search Tree
程序员文章站
2022-03-16 08:42:37
...
题目描述
Given a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.
思路1
中序遍历二叉树,同时新建一颗二叉树,随着遍历的进行,不断往右孩子中填值。
代码
class Solution {
private TreeNode newTree = new TreeNode();
private TreeNode index = newTree;
public TreeNode increasingBST(TreeNode root) {
if (root == null) return null;
increasingBST(root.left);
newTree.right= new TreeNode(root.val);
newTree = newTree.right;
increasingBST(root.right);
return index.right;
}
}
思路2
不用新建树,直接修改指针。
代码
class Solution {
TreeNode prev=null, head=null;
public TreeNode increasingBST(TreeNode root) {
if(root==null) return null;
increasingBST(root.left);
if(prev!=null) {
root.left=null; // we no longer needs the left side of the node, so set it to null
prev.right=root;
}
if(head==null) head=root; // record the most left node as it will be our root
prev=root; //keep track of the prev node
increasingBST(root.right);
return head;
}
}
推荐阅读
-
二叉搜索树(Binary Search Tree)(Java实现)
-
Java/897. Increasing Order Search Tree 递增顺序查找树
-
(Java)leetcode-897 Increasing Order Search Tree
-
LeetCode - 897 - 递增顺序查找树(increasing-order-search-tree)
-
leetcode 897. Increasing Order Search Tree(增序搜索树)
-
二叉搜索树(Binary Search Tree)(Java实现)
-
leetcode学习笔记897 Increasing Order Search Tree