题解 | #树查找#按下标输出或者递归建树加递归遍历

树查找

https://www.nowcoder.com/practice/9a10d5e7d99c45e2a462644d46c428e4

//C++版代码
#include <iostream>
#include <cmath>
using namespace std;
int main() {
    int n;
    cin >> n;
    int nums[n + 1];
    for (int i = 1; i <= n; i++) cin >> nums[i];
    int d;
    cin >> d;
    if (d <= ceil(log2(n + 1))) {
        for (int i = (int) pow(2, d - 1); i <= min((int) pow(2, d) - 1, n);
                i++) cout << nums[i] << " ";
    } else {
        cout << "EMPTY";
    }
    return 0;
}
//Java版代码
import java.util.Scanner;
public class Main {
    private static String[] nums;
    private static int targetDepth;
    private static boolean flag = false;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        nums = new String[n];
        for (int i = 0; i < n; i++) nums[i] = sc.next();
        targetDepth = sc.nextInt();
        getTree(buildTree(0), 1);
        if (!flag) System.out.println("EMPTY");
    }
    private static TreeNode buildTree(int index) {
        if (index >= nums.length) return null;
        TreeNode node = new TreeNode(nums[index]);
        node.left = buildTree(index * 2 + 1);
        node.right = buildTree(index * 2 + 2);
        return node;
    }
    private static void getTree(TreeNode root, int curDepth) {
        if (root == null) return;
        if (curDepth == targetDepth) {
            System.out.print(root.val + " ");
            flag = true;
        }
        getTree(root.left, curDepth + 1);
        getTree(root.right, curDepth + 1);
    }
    private static class TreeNode {
        private final String val;
        private TreeNode left = null, right = null;
        private TreeNode(String val) {
            this.val = val;
        }
    }
}

全部评论

相关推荐

06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
无实习如何秋招上岸
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务