在Narasimha Karumanchi简化数据结构和算法的书中, 这是用于查找树的最大深度的代码。树的最大深度,使用队列
由于某种原因,他向队列提供null
。我不懂为什么。删除它会破坏代码。
我想知道作者为什么要加入null
,如果可以这样解决问题,我们可以在不添加null
的情况下解决同样的问题。
源代码:
public class MaxDepthInBinaryTreeWithLevelOrder {
// Returns the depth of this binary tree. The depth of a binary tree is the
// length of the longest path from this node to a leaf. The depth of a
// binary tree with no descendants (that is, just a leaf) is zero.
public int maxDepthLevelOrder(BinaryTreeNode root){
if(root == null)
return 0;
int maxDepth = 1;
Queue<BinaryTreeNode> q = new LinkedList<BinaryTreeNode>();
q.offer(root);
q.offer(null); // <----------- 'NULL' added Here
while(!q.isEmpty()){
BinaryTreeNode tmp = q.poll();
if(tmp != null){
if(tmp.getLeft() != null)
q.offer(tmp.getLeft());
if(tmp.right != null)
q.offer(tmp.right);
}else{
if(!q.isEmpty()){
++maxDepth;
q.offer(null); // <--------- Here
}
}
}
return maxDepth;
}
}
我不明白这个算法(也许如果我花了更多的时间,我可以弄清楚),但似乎他使用'null'作为某种标记。 – ajb
我认为这是一个广度优先搜索。该算法搜索树的宽度。一个'null'标记每个宽度的结束,所以当找到'null'时,深度计数器就会增加。 – markspace