【问题标题】:Given a node Burn the binary tree给定一个节点烧掉二叉树
【发布时间】:2021-04-05 03:22:24
【问题描述】:

我正在尝试实现给定的问题enter link description here,但没有得到所需的输出我的程序有什么问题。以编程方式,我试图查找目标 no 是否存在于左子树或右子树中,如果它存在于左子树中,则从左侧返回 1 并将其子节点推入队列,右树也类似。

Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
static Queue<Node> q=new LinkedList<Node>()
    burnTheNodes(root,2);
    int size=q.size();
    for(int i=0;i<size;i++) {
        Node curr=q.remove();
        System.out.println(curr.data);
    }
     
private static int burnTheNodes(Node root,int num) {
    
    if(root==null) {
        return 0;
    }
    if(root.data==num) {
            System.out.println(root.data);
            if(root.left!=null) {
                q.add(root.left);
            }
            if(root.right!=null) {
                q.add(root.right);
            }
            return 1;
        }
    int a=burnTheNodes(root.left, num);
    if(a==1) {
        int size=q.size();
        for(int i=0;i<size;i++) {
            Node curr=q.remove();
            System.out.print(curr.data+"-");
            if(curr.left!=null) {
                q.add(curr.left);
            }
            if(curr.right!=null) {
                q.add(curr.right);
            }
        }
        
        if(root.right!=null) {
            q.add(root.right);
        }
        System.out.println(root.data);
        return 1;
    }
    
    int b=burnTheNodes(root.right, num);
    if(b==1) {
        int size=q.size();
        for(int i=0;i<size;i++) {
            Node curr=q.remove();
            System.out.println(curr.data);
            if(curr.left!=null) {
                q.add(curr.left);
            }
            if(curr.right!=null) {
                q.add(curr.right);
            }
        }
        
        if(root.left!=null) {
            q.add(root.left);
        }
        System.out.println(root.data);
        return 1;
    }
    return 1;
    
}

输出是 - 它缺少节点 6 和 7。 2 4-5-1 3

【问题讨论】:

  • q 未声明。
  • 感谢您指出这一点,但我错过了在此处粘贴代码时这不是实际问题,问题在逻辑中的某个地方。

标签: java tree binary-tree


【解决方案1】:

问题在于,在main 的最后一个循环中,您不会像在burnTheNodes 中的类似循环中那样 子级添加到队列中。

只要队列中有条目,您就应该继续该过程,只要提取的节点有子节点,就应该继续添加条目。

【讨论】:

    猜你喜欢
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多