【问题标题】:longest path in binary tree and return node values二叉树中的最长路径并返回节点值
【发布时间】:2014-09-05 23:10:26
【问题描述】:

我试图在二叉树中找到最长的路径并打印出来。例如:对于树:
3
/ \
4 5
/ \
6 2

我想打印 3,5,6 或 3,5,2。

我有以下代码来获取最大深度:

public int getMaxDepth(Node<Integer> node){ 
   if (node == null) return 0;
      return 1 + Math.max(node.left, node.right);
} 

但是,在获得深度后,我不确定如何获得确切的路径。我正在考虑使用堆栈,但我不确定如何使用它。任何帮助都会很棒

【问题讨论】:

    标签: tree binary-tree


    【解决方案1】:

    不确定您使用的是什么语言。有几种方法可以做到这一点。我会做类似的事情:

    public List<Node<Integer>> getMaxPath(Node<Integer> current, List<Node<Integer>> list){
        if (current == null)
            return list;
    
        list = list.copy();
        list.append(current);
        List<Node<Integer>> left = getMaxPath(node.left, list);
        List<Node<Integer>> right = getMaxPath(node.right, list);
    
        return left.length > right.length ? left : right;
    } 
    
    getMaxPath(tree.head, new List<Integer>())
    

    【讨论】:

      猜你喜欢
      • 2021-09-19
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      • 2021-12-05
      • 2021-12-30
      • 2019-12-06
      相关资源
      最近更新 更多