2 回答
TA贡献1812条经验 获得超5个赞
您基本上可以使用相同的功能以预购方式进行访问,并进行一些修改:
void findNextInPreOrder(TreeNode node, int key) {
if (node == null) {
return;
}
if (node.value == key) {
if(node.left != null){
System.out.print("Next is on left: " + node.left.value);
} else if (node.right != null){
System.out.print("Next is on right: " + node.right.value);
} else {
System.out.print("There is no next node.");
}
}
findNextInPreOrder(node.left); /* then recur on left subtree */
findNextInPreOrder(node.right); /* now recur on right subtree */
}
TA贡献1866条经验 获得超5个赞
我还添加了一个“else”语句,因为这似乎对我的实现有所帮助:
void findNextInPreOrder(Node node, int key) {
if (node == null) {
return;
}
if (node.value == key) {
if (node.left != null) {
System.out.print("Next is on left: " + node.left.value);
} else if (node.right != null) {
System.out.print("Next is on right: " + node.right.value);
} else {
System.out.print("There is no next node.");
}
} else {
findNextInPreOrder(node.left, key);
/* then recur on left subtree */
findNextInPreOrder(node.right, key);
/* now recur on right subtree */
}
}
添加回答
举报