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

树查找

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;
        }
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 14:00
不想多说了,什么逆天HR,还要教我礼貌😂
机械打工仔:这不纯傻卵吗,他还操心上别人老板了
投递BOSS直聘等公司7个岗位
点赞 评论 收藏
分享
06-26 17:24
已编辑
宁波大学 golang
迷失西雅图:别给,纯kpi,别问我为什么知道
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 16:15
我应届生,去年10月份开始在这家公司实习,到今年10月份正好一年想(实习+试用期),在想要不要提前9月份就离职,这样好找工作些,但又差一个月满一年,又怕10月份国庆回来离职,容易错过了下半年的金九银十,到年底容易gap到年后
小破站_程序员YT:说这家公司不好吧,你干了快一年 说这家公司好吧,你刚毕业就想跑路说你不懂行情吧,你怕错过金九银十说 你懂行情吧,校招阶段在实习,毕业社招想换工作 哥们,我该怎么劝你留下来呢
应届生,你找到工作了吗
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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