Reputation: 1399
As stated in the title, I'm trying to solve this problem by only counting nodes in a BST that have both left and right children. I'm struggling to think of the logic to solve this.
I thought of something like this.
First, check if the root is null or if it has any null children. Next, traverse the tree going right and continue to check the children, increment a counter when the conditions are met. But what happens when I reach the end node and need to go back to a node that had a left child to traverse? I had a temp node to keep track of the most previous parent, but what about when I need to go up more than one level? I'm assuming the answer to this problem is to recursively solve it, but I don't even know where to begin.
Here's what I have:
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;
}
I'm still struggling to think recursively when problem solving, in addition to my question, how do you learn to think recursively? Just a ton of practice, or is there some tricks and tips that you use to solve problems?
Upvotes: 1
Views: 3334
Reputation: 505
First let us create representation of your Node class
class Node {
public Node left;
public Node right;
public Node(){}
public Node(Node left, Node right) {
this.left = left;
this.right = right;
}
}
Then we write our recusrive function and client that uses your function
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));
}
}
Upvotes: 1
Reputation: 14164
Rather than using a temp variable to hold the previous node -- which would only work for a depth of 1 -- call the same function on the child nodes.
Recursive tree traversal might look something like this:
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);
The execution callstack will then hold recursive invocations of the function, each with their appropriate context. When the top-level call returns, it will have summed the answer for the entire tree/ or subtree it was called on.
Put appropriate logic for your BST "node has both left & right children" in, instead of the constant 1.
Upvotes: 1