[英]BST - counting nodes with left and right children
如标题中所述,我试图通过仅计算BST中同时具有左右子节点的节点来解决此问题。 我正在努力思考解决这个问题的逻辑。
我想到了这样的事情。
首先,检查根是否为空或子级是否为空。 接下来,遍历右转的树并继续检查子级,在满足条件时增加一个计数器。 但是,当我到达末端节点并需要返回到有一个左孩子要遍历的节点时会发生什么? 我有一个临时节点来跟踪最近的父级,但是当我需要上一层以上时该怎么办? 我以为这个问题的答案是递归地解决它,但我什至不知道从哪里开始。
这是我所拥有的:
public int fullNodes() {
int count = 0;
Node n = root;
Node temp = null;
if (n == null || n.left == null && n.right == null) return count;
count++; //increment count, since the root has children on both sides
temp = n; //hold the previous place
n = n.right; //go right
//Now what?
return count;
}
解决问题时,我仍在努力进行递归思考,除了我的问题之外,您如何学习递归思考? 只是大量的实践,还是您使用一些技巧来解决问题?
在子节点上调用相同的函数,而不是使用temp变量来保存前一个节点(只能在深度为1的情况下使用)。
递归树遍历可能看起来像这样:
public int countSomething (Node node) {
// Self;
//
int result = 1; // use your required logic here
// Children;
//
if (node.left != null)
result += countSomething( node.left);
if (node.right != null)
result += countSomething( node.right);
// done.
return result;
}
// example usages
int treeTotal = countSomething( rootNode);
int subtreeTotal = countSomething( subtree);
然后,执行调用堆栈将保留函数的递归调用,每个调用都具有其适当的上下文。 当顶级调用返回时,它将汇总被调用的整个树或子树的答案。
为您的BST“节点同时具有左右两个子节点”输入适当的逻辑,而不是常量1。
首先让我们创建您的Node类的表示形式
class Node {
public Node left;
public Node right;
public Node(){}
public Node(Node left, Node right) {
this.left = left;
this.right = right;
}
}
然后,我们编写我们的可恢复函数和使用您函数的客户端
public class Main {
public static int countNodes(Node root) {
if(root!=null && root.left!=null && root.right!=null) {
return 1+countNodes(root.left)+countNodes(root.right);
}
return 0;
}
public static void main(String[] args) {
Node right = new Node();
Node left = new Node();
Node root = new Node(left, right);
root.right = new Node(new Node(), new Node());
System.out.println(countNodes(root));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.