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

树查找

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

全部评论

相关推荐

不愿透露姓名的神秘牛友
10-05 10:13
已编辑
HHHHaos:让这些老登来现在秋招一下,简历都过不去
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务