C++ 在树结构中搜索节点

C++ 在树结构中搜索节点,c++,tree,structure,traversal,C++,Tree,Structure,Traversal,我需要帮助查找和返回一个通用树结构中的节点。每个节点可以有两个以上的子节点,因此它不是二叉树。我得到了以下代码,这个元素对象有一个包含其子元素的列表,我在main中创建了一个元素节点指针,并使用它添加和搜索子元素。这是一个学校项目,但我不是在寻找答案,答案不会有坏处。任何关于如何解决这个问题的建议都将不胜感激,谢谢 #pragma once #include <iostream> #include <list> #include <sstream> usin

我需要帮助查找和返回一个通用树结构中的节点。每个节点可以有两个以上的子节点,因此它不是二叉树。我得到了以下代码,这个元素对象有一个包含其子元素的列表,我在main中创建了一个元素节点指针,并使用它添加和搜索子元素。这是一个学校项目,但我不是在寻找答案,答案不会有坏处。任何关于如何解决这个问题的建议都将不胜感激,谢谢

#pragma once
#include <iostream>
#include <list>
#include <sstream>

using namespace std;

class Element
{
  private:
  list<Element*> children;
  char* _tag;
  int _value;
  // private methods
  public:
  // default constructor
  Element();
  // non-default constructors
  Element( char* name); // value is set to -99 if not given
  Element(char* name, char* value);
  // destructor, must recursively destruct its children
  // and release the memory allocated for _tag
  ~Element();
  // ostream operator ( pre-order traversal)
  friend ostream&  operator << (ostream& out, const Element& E);
  void display_xml(); // print out the tree in xml-- format
  void addChild( Element* child); // add a child
  // Find the first element such that _tag == tag
  // returns “this” pointer of this element
  Element* findTag( char* tag);
  char* getName();
  int getValue();
  void setName(char* name);
  void setValue( int value);
  int height(); //b return the height
  int size(); // return the size
  // other methods
};
这是我在解决方案上的最佳尝试,它有明显的问题,但我对所有这些都是新手,对正确的解决方案进行一些解释,或者一些示例代码将非常有用

Element* Element::findTag(char* tag)
{
    list<Element*> temp = children;
    int s = temp.size();

    if(getName() == tag)
    {
        return this;
    }
    else
    {
        for(int i = 0; i < s; i++)
        {
            findTag((*temp.front()).getName());
            temp.pop_front();
        }
    }

}

我将为您提供一个伪代码,用于在根目录树中搜索值为val的节点:


谢谢你的回复!
find(Node root, val)
    if(root.value == val) return root         //-- if the recursion found the node we are searching for
else
    for every child x of root                //-- re-cursing on the children of root 
        if(find(x, val) != null) return x    //-- if one of the calls found the node we are searching for
    return null                              //-- if we did not find the node we want in the sub-tree rooted at root