图解:LeetCode897. 递增顺序搜索树(递归解法)
解题思路
排列成一个递增顺序搜索树 即 将root移至root左子树的最右边的叶子结点的right上,
并且root的right等于右子树的最左叶子节点
例:root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
1.将root移至root左子树的最右边的叶子结点的right上
2.root的right等于右子树的最左叶子节点
3.然后递归处理root原来的左节点和右节点即可
第一次画图,画的不好,请见谅!
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode increasingBST(TreeNode root) {
if(root == null) return null;
TreeNode cur = root;
TreeNode left = root.left;
if(root.left != null) {
cur =cur.left;
while(cur.right != null) {
cur = cur.right;
}
root.left = null;
cur.right = root;
}
if(root.right != null) {
root.right = increasingBST(root.right);
}
return left == null ? root : increasingBST(left);
}
}
对你有帮助的话 不妨点个赞吧!