递归搜索非二叉树中的节点 [英] Recursive search for a node in non-binary tree

查看:115
本文介绍了递归搜索非二叉树中的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在非二叉树中搜索一个项目(任何节点都可以有n个子节点)并立即退出递归。有问题的节点可以是任何节点,而不仅仅是叶子。

I want to search for an item in non-binary tree (any node can have n - children) and exit from recursion immediately. The node in question can be any node, not only leafs.

这是我的代码,但我没有完全搜索。

This is my code but i don't get complete search.

private nNode recursiveSearch(data gi,nNode node){
        if (node.getdata()==gi)
            return node;
        nNode[] children = node.getChildren(); 
        if (children.length>0)
        for (int i = 0; i < children.length; i++) {         
            return recursiveSearch(gi, children[i]);
        }
        return null;
 }

nNode包含:

ArrayList mChildren; (它是孩子们)

和数据对象。

ArrayList mChildren ; (it's children)
and data object.

推荐答案

探索第一个孩子后不应退出。对于循环,前面的 if 语句不需要。

You shouldn't exit after exploring the first child. You don't need the if statement in front of the for loop.

private nNode recursiveSearch(data gi,nNode node){
    if (node.getdata()==gi)
        return node;
    nNode[] children = node.getChildren(); 
    nNode res = null;
    for (int i = 0; res == null && i < children.length; i++) {         
        res = recursiveSearch(gi, children[i]);
    }
    return res;
 }

这篇关于递归搜索非二叉树中的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆