在树结构中搜索节点

时间:2015-04-03 01:44:05

标签: c++ tree structure traversal

我需要帮助查找并返回"节点"在一般的树结构中。每个节点可以有2个以上的子节点,因此它不是二叉树。我已经获得了以下代码,这个Element对象有一个包含其子节点的列表,我在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();
        }
    }

}

1 个答案:

答案 0 :(得分:0)

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

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
相关问题