⭐北邮复试刷题LCR 052. 递增顺序搜索树__DFS (力扣119经典题变种挑战)

LCR 052. 递增顺序搜索树

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

示例 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]
提示:

树中节点数的取值范围是 [1, 100]

0 <= Node.val <= 1000

题解:

本题对所给二叉树中序遍历即可,即按照左根右,当访问根时,创建节点即可;

注意因为Java中创建对象和创建变量不同,创建同样名字的变量会导致上次创建的变量没有东西做依准故找不到,而创建对象会分配地址因此即使创建同样名字的对象也可通过地址找到;

代码:

java 复制代码
/**
 * 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 {
    TreeNode res = null;
    TreeNode index = null;

    public TreeNode increasingBST(TreeNode root) {
        dfs(root);
        return res;
    }

    public void dfs(TreeNode node){
        if(node.left != null)
            dfs(node.left);
        if(res == null){
            res = new TreeNode();
            res.val = node.val;
            index = res;
        }
        else{
            TreeNode temp = new TreeNode();
            temp.val = node.val;
            index.right = temp;
            index = index.right;
        }
        if(node.right != null)
            dfs(node.right);
    }
}

结果:

相关推荐
超级大只老咪6 小时前
数组相邻元素比较的循环条件(Java竞赛考点)
java
hh随便起个名6 小时前
力扣二叉树的三种遍历
javascript·数据结构·算法·leetcode
小浣熊熊熊熊熊熊熊丶6 小时前
《Effective Java》第25条:限制源文件为单个顶级类
java·开发语言·effective java
毕设源码-钟学长6 小时前
【开题答辩全过程】以 公交管理系统为例,包含答辩的问题和答案
java·eclipse
啃火龙果的兔子6 小时前
JDK 安装配置
java·开发语言
星哥说事6 小时前
应用程序监控:Java 与 Web 应用的实践
java·开发语言
派大鑫wink6 小时前
【JAVA学习日志】SpringBoot 参数配置:从基础到实战,解锁灵活配置新姿势
java·spring boot·后端
xUxIAOrUIII7 小时前
【Spring Boot】控制器Controller方法
java·spring boot·后端
Dolphin_Home7 小时前
从理论到实战:图结构在仓库关联业务中的落地(小白→中级,附完整代码)
java·spring boot·后端·spring cloud·database·广度优先·图搜索算法
醇氧7 小时前
org.jetbrains.annotations的@Nullable 学习
java·开发语言·学习·intellij-idea