【问题标题】:How to get depth of a node in one recursive search in non-binary tree如何在非二叉树的一次递归搜索中获取节点的深度
【发布时间】:2014-02-11 06:39:11
【问题描述】:

根据Recursive search for a node in non-binary tree,我知道如何实现递归搜索,但是如何获得该节点的深度?

我想我应该为每个递归添加一个计数器,但我不知道应该在哪里添加这个计数器.....

谢谢

【问题讨论】:

    标签: java data-structures recursion tree


    【解决方案1】:

    这里是带有 cmets 的部分代码:

    public class Tree
    {
        private Node root;
    
        public int findDepth(int searchNodeValue) {
            List<Node> nodesAtCurrentLevel = Collections.singletonList(root);
    
            return recursiveSearch(0, searchNodeValue, nodesAtCurrentLevel);
        }
    
        public int recursiveSearch(int level, int searchNodeValue, List<Node> nodesAtCurrentLevel) {
            List<Node> nodesAtNextLevel = new ArrayList<Node>();
    
            // Check if searchNode matches any node at current level
            for (Node node : nodesAtCurrentLevel) {
                // If it matches, we have found the node, return current level
                if (node.getValue() == searchNodeValue) {
                    return level;
                }
    
                // Add children of all nodes at current level in nodesAtNextLevel
                if (node.hasChildren()) {
                    nodesAtNextLevel.addAll(node.getChildren());
                }
            }
    
            // searchNode is not found at current level, increment level and continue search at next level if next level exists in tree
            if (!nodesAtNextLevel.isEmpty()) {
                return recursiveSearch(level + 1, searchNodeValue, nodesAtNextLevel);
            }
    
            // We have traversed entire tree. Node not found. Return -1
            return -1;
        }
    }
    
    class Node
    {
        private int value;
    
        private List<Node> children = new ArrayList<Node>();
    
        public Node(int value) {
            this.value = value;
        }
    
        public boolean hasChildren() {
            return children.isEmpty();
        }
    
        public int getValue() {
            return value;
        }
    
        public List<Node> getChildren() {
            return children;
        }
    }
    

    【讨论】:

      【解决方案2】:

      编辑

      -- 让递归函数获得输入级别。从 0/-1 开始。返回一个对象;该对象具有节点和级别。递归函数的每次传递都会增加传入的级别并将其设置在返回对象中。

      -- 将级别传递给递归函数。从 0/-1 开始。维护一个全局变量(或定义为非本地函数的变量,以便在函数的每次迭代中访问相同的变量;即变量不在堆栈上而是在堆上。我希望这件事在Java,不需要进一步解释)。在递归函数开始时将其设置为(1 + 传入级别)。这不是线程安全的。

      // 原始答案的想法是将级别作为参考传递并在递归函数中增加它。显然,在 Java 中这样做很乏味。

      【讨论】:

      • “通过引用传递变量” - 你知道问题是关于 Java 的吧? (我知道可以在 Java 中模拟传递引用,但提及传递引用应该与解释和/或链接一起使用)
      • 好的。删除了按引用传递位。换成别的东西了。
      猜你喜欢
      • 2012-01-26
      • 2015-04-08
      • 2010-11-03
      • 2012-10-10
      • 2023-03-29
      • 2021-02-13
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多