我需要在二叉树中打印节点的祖先。例如,节点7的祖先为1,3。我已经编写了下面的代码,但输出结果为7.您能否在此代码中提出问题?
1
/ \
2 3
/ \ / \
4 5 6 7
public static String findAncestor(BinaryTreeNode root , int number, boolean matched) {
if (root != null) {
int rootData = root.getData();
BinaryTreeNode left = root.getLeft();
BinaryTreeNode right = root.getRight();
if (left != null && right != null) {
return findAncestor (root.getLeft(), number, matched ) + findAncestor (root.getRight(), number, matched);
}
if (left != null) {
return findAncestor (root.getLeft(), number, matched ) ;
}
if (right != null) {
return findAncestor (root.getRight(), number, matched ) ;
}
if (rootData == number) {
matched = true;
return String.valueOf(rootData);
}
if (matched) {
return String.valueOf(rootData);
}
}
return "";
}
答案 0 :(得分:3)
public boolean findAncestorPath(List<Integer> ancestors, BinaryTreeNode node, int number) {
if (node == null)
return false;
int data = node.getData();
if (data == number)
return true;
if (findAncestorPath(ancestors, node.getLeft(), number)) {
ancestors.add(data);
return true;
}
if (findAncestorPath(ancestors, node.getRight(), number)) {
ancestors.add(data);
return true;
}
return false;
}
然后你将其称为(你也应该把它包装在一个函数中):
List<Integer>() ancestors = new ArrayList<Integer>();
boolean found = findAncestorPath(ancestors, root, number);
请注意,ancestor
列表会被颠倒。
答案 1 :(得分:0)
这是Java实现
public static List<Integer> ancestors(BinaryTreeNode<Integer> root, Integer target) {
List<Integer> result = new ArrayList<Integer>();
findAncestors(root, target, result);
return result;
}
private static boolean findAncestors(BinaryTreeNode<Integer> node, Integer target, List<Integer> result) {
if (node == null) {
return false;
}
if (node.getData() == target) {
return true;
}
if (findAncestors(node.getLeft(), target, result) || findAncestors(node.getRight(), target, result)) {
result.add(node.getData());
return true;
}
return false;
}
这是单元测试用例
@Test
public void allAncestors() {
BinaryTreeNode<Integer> root = buildTree();
List<Integer> ancestors = BinaryTreeUtil.ancestors(root, 6);
assertThat(ancestors.toArray(new Integer[0]), equalTo(new Integer[]{5,2,1}));
}
答案 2 :(得分:-1)
这段代码适用于为所有祖先提供特定节点,节点是根节点,value是我们必须找到所有祖先的节点的值。
static boolean flag=false;
static void AnchersterOf(AnchesterNode node,int value) {
// TODO Auto-generated method stub
if(node==null)
return ;
if(node.value==value){
flag=true;
return;
}
if(flag==false){
AnchersterOf(node.left,value);
if(flag==true){
AnchersterOf(node,value);
} if(flag==true)
System.out.println(node.value);
AnchersterOf(node.right,value);
if(flag==true)
System.out.println(node.value);
}
}