【问题标题】:breadth first tree, max distance from root to leaf广度优先树,从根到叶的最大距离
【发布时间】:2014-02-24 21:31:39
【问题描述】:

我正在尝试计算二叉树从根到叶的最长路径中的节点数。 鉴于以下代码,我有两个问题:

1) 以下列方式使用队列是否等同于树的广度优先遍历? 2)这是一种准确的方法吗?函数原型是固定的,所以如果我不能在递归调用之间传递状态(如 depth_count),我就看不到递归执行它。

函数为树 {0,2,4,1,#,3,-1,5,1,#,6,#,8} 输出 5,应该输出 4。

int maxDepth(TreeNode *root){ 
    int depth_count=0, i;
    queue<TreeNode*> ns;
    TreeNode* curr;

    if (root){
        ns.push(root);        

       while (!ns.empty()){
            depth_count++;
            for (i=0; i < ns.size(); i++){
                curr = ns.front();
                if (curr->left)
                    ns.push(curr->left);
                if (curr->right)
                    ns.push(curr->right);
                ns.pop();
            }

        }//endwhile
    }//endif
    return depth_count;
}

【问题讨论】:

    标签: tree breadth-first-search depth


    【解决方案1】:

    我不认为 for 循环看起来有点奇怪是正确的。如果您不想以递归方式和广度优先执行此操作,我会将深度与节点一起保存在队列中。

    int maxDepth(TreeNode *root){ 
      int depth=0;
      queue<pair<TreeNode*, int> > ns;
      pair<TreeNode*, int> curr;
    
      if (root){
        ns.push(make_pair(root, 1));
    
       while (!ns.empty()){
          curr = ns.front();
          depth = max(depth, curr.second);
          if (curr.first->left)
            ns.push(make_pair(curr.first->left, curr.second+1));
          if (curr.first->right)
            ns.push(make_pair(curr.first->right,curr.second+1));
          ns.pop();
    
        }//endwhile
      }//endif
      return depth;
    }
    

    编辑:另一种方法是在 for 循环中使用您获得但不使用 ns.size() 的代码,这会随着您在队列中添加和删除节点而增长或缩小,并且您不会遍历单个深度.相反,您需要在进入 for 循环之前保存 ns.size(),以便每次进入 for 循环时只遍历树的一个深度。

    【讨论】:

    • 我知道你要带这对东西去哪里。这可能会有所帮助。 for 循环的想法是,在进入循环时……你只有第 n 级的节点。假设第 n 级有 3 个节点,每个节点有 2 个子节点。然后输入:对于 1、2、3:添加他们的每个孩子,然后制作 3 个 pop。重新进入while循环,ns包含了所有@n+1层的节点(ns.size() == 6)
    • @dagan 是的,你可以这样做,但你需要这样做,我后来发现你的 for 循环有什么问题是你不能在循环中使用 ns.size() 因为你正在改变ns的大小。您需要做的是在进入 for 循环之前保存 ns.size() 。 int stop = ns.size(); for (i=0; i &lt; stop; i++){...
    猜你喜欢
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多