广度第一棵树,从根到叶子的最大距离

时间:2014-02-01 00:55:22

标签: tree breadth-first-search depth

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

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;
}

1 个答案:

答案 0 :(得分:2)

我不认为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循环时只遍历树的单个深度。