简体   繁体   English

检测树中的节点是否有子节点或已访问子节点

[英]Detecting if a node in a tree has child(s) or child nodes have been visited

I am struggling with the logic behind detecting nodes in my tree exists or have been visited. 我正在为检测树中存在或已被访问的节点背后的逻辑而苦苦挣扎。

I have a tree with nodes (a node has a left and right child node). 我有一棵带有节点的树(一个节点有一个左右子节点)。

I want to check 2 things on a node: If there are no child nodes If there are child(s) nodes I want to check if they have been visited. 我想检查一个节点上的2件事:如果没有子节点如果有子节点,我想检查是否已被访问。

I currently have a large condition which I hate the look of. 我目前病情大,我讨厌它的外观。 Is there a way I can simplify it? 有什么办法可以简化它吗?

public boolean finished(){
      return right == null && left == null || ((right != null && right.visited && (left != null && left.visited))
}

I want finished() to be true: If a right and left node dont exist If a right exists and has been visited If a left exists and has been visited 我希望finished()为true:如果左右节点不存在如果右边存在并且已经被访问如果左边存在并且已经被访问

I think I also need an OR so if a right exists AND visited AND left is null 我想我还需要一个OR因此,如果存在的权利AND走访AND左边是空

I'm a bit confused :S 我有点困惑:S

I think this may be what you are after 我想这可能就是你所追求的

if( (right == null || right.visited) && ( left == null || left.visited) )

So for each child node if it is either empty or has been visited then you are finished. 因此,对于每个子节点,如果它为空或已被访问,那么您就可以完成。

This covers the cases 这涵盖了案例

Right == null; Left == null; 
Right == null; Left.visited; 
Right.visited; Left == null; 
Right.visited; Left.visited;

which I think given the description is the cases you wanted to check for. 我认为给出描述就是您要检查的情况。

The simplest approach to "visited" is to put a "visited" flag in your nodes. “已访问”的最简单方法是在节点中放置“已访问”标志。 Reset all flags to start, then do your tree traversal and set the flags as you visit them. 重置所有标志开始,然后遍历树并在访问它们时设置标志。

To avoid having to reset the "visited" flags after every use, make the "flag" an integer, and keep a global counter which is incremented each time you do a scan where you need the visited flag: 为避免每次使用后都必须重置“已访问”标志,请将“标志”设置为整数,并保留一个全局计数器,该计数器在每次进行扫描时都会在需要访问标志的地方递增:

boolean haveVisited() {
   return visitedFlag == globalVisitedCounter;
}

void markVisited() {
   visitedFlag = globalVisitedCounter;
}

You do need to, in theory, have logic to scan all the nodes in the tree and reset them when the global counter wraps, but in practice that's usually not needed. 从理论上讲,您确实需要逻辑来扫描树中的所有节点,并在全局计数器换行时将其重置,但是实际上通常不需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM