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

树查找

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-15 22:27
已编辑
门头沟学院 C++
罗格镇的小镇做题家:我投了hr打电话来说学历太低了不符合要求,建议投荣耀,结果荣耀也投了一定水花没有,非本211硕
投递华为等公司10个岗位
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务