gpt4 book ai didi

java - 删除二叉树中的所有叶子

转载 作者:行者123 更新时间:2023-12-02 05:34:23 25 4
gpt4 key购买 nike

此方法应该从二叉树(没有左右分支)中删除所有叶子,但由于某种原因,它只从二叉树中删除叶子的一个实例。这是为什么?我认为基本情况负责通过将parent.left或parent.right设置为null来切断与父节点的联系。如果它不是叶子,它将递归调用,直到遇到叶子。

这是我到目前为止所拥有的:

 private IntTreeNode overallRoot; // Beginning of the chain of nodes


// post: Removes All leaves from a tree
public void removeLeaves() {
if (overallRoot == null) { // If empty tree
return;
} else {
removeLeaves(overallRoot);
}

}

// helper for removeLeaves
private void removeLeaves(IntTreeNode root) {
if (root.left != null) { // tests left root
if (root.left.left == null && root.left.right == null) { // if next left node is leaf (base case)
root.left = null; // delete
} else if (root.left.left != null && root.left.right == null) { // If next right is empty
removeLeaves(root.left.left); // only check second left
} else if (root.left.right != null && root.left.left == null) { // If next left is empty
removeLeaves(root.left.right);
} else if (root.left.left != null && root.left.right != null) { // If next left/right isn't empty
removeLeaves(root.left.left);
removeLeaves(root.left.right);
}
}

if (root.right != null) {
if (root.right.left == null && root.right.right == null) { // if next left node is leaf (base case)
root.right = null; // delete
} else if (root.right.left != null && root.right.right == null) { // If next right is empty
removeLeaves(root.right.left); // only check second left
} else if (root.right.right != null && root.right.left == null) { // If next left is empty
removeLeaves(root.right.right);
} else if (root.right.left != null && root.right.right != null) { // If next left/right isn't empty
removeLeaves(root.right.left);
removeLeaves(root.right.right);
}
}
}

这是单个节点类:

public class IntTreeNode {
public int data;
public IntTreeNode left;
public IntTreeNode right;

// constructs a leaf node with given data
public IntTreeNode(int data) {
this(data, null, null);
}

// constructs a branch node with given data, left subtree,
// right subtree
public IntTreeNode(int data, IntTreeNode left, IntTreeNode right) {
this.data = data;
this.left = left;
this.right = right;
}
}

最佳答案

以自下而上的方式对树木进行结构修改通常会更清晰:

public IntTreeNode removeLeaves(IntTreeNode root) {
if (root == null || root.isLeaf()) {
return null;
}
root.left = removeLeaves(root.left);
root.right = removeLeaves(root.right);
return root;
}

关于java - 删除二叉树中的所有叶子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25151991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com