Java – find all the leaves through binary search tree iteration

I'm new to trees. I'm trying to create a "leaf iterator" I think it should put No Left and All nodes with the right value are placed on a stack, but I don't know how to even do it correctly I've tried to search it, but every example I've come to starts with the leftmost leaf and then goes to P = node Parent, I avoid linking to the parent node of the node

I don't understand how I can fundamentally start over, through the grapevine instead of visiting the grapevine again and again

edit

I see people suggest using recursive methods to solve this problem, and I agree now But I've been trying to find an iterator class method to solve this problem for some time, and I still want to know if it's possible and how!

Solution

Use recursion:

public void visitNode(Node node) {
    if(node.left != null) {
        visitNode(node.left);
    }
    if(node.right != null) {
        visitNode(node.right);
    }
    if(node.left == null && node.right == null) {
        //OMG! leaf!
    }
}

Start it by providing root:

visitNode(root);

In order to convert it to iterator < node > you must convert recursion into a loop and then use the state to traverse Extraordinary, but it should give you a lot of fun

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>