二叉树其他操作(复制,层数,相等判断)
1.二叉树复制
复制二叉树
1 //复制一棵二叉树
2 template<class T> tree<T>::tree(const tree<T> &obj)
3 {
4
5 this->root=copy(obj.root);
6 }
7
8 template<class T> tree<T>& tree<T>::operator=(const tree<T> &obj)
9 {
10 if (this!=&obj)
11 {
12 this->root=copy(obj.root);
13 }
14
15 return *this;
16
17 }
18
19 template<class T> tree_node<T> * tree<T>::copy(const tree_node<T> *p)
20 {
21 if (p)
22 {
23 tree_node<T> *node=new tree_node<T>;
24 if (node==NULL)
25 {
26 cout<<"out of member"<<endl;
27 exit(1);
28 }
29 node->value=p->value;
30 node->lchild=copy(p->lchild);
31 node->rchild=copy(p->rchild);
32 return node;
33 }
34 else
35 return NULL;
36 }
2.统计节点数
统计节点数
1 //统计节点数
2 template<class T> int tree<T>::nodes()
3 {
4 int count=0;
5
6 //中序遍历
7 if (root)
8 {
9 tree_node<T> *ptr=root;
10 stack<tree_node<T> *> stack;
11
12 while (1)
13 {
14 while (ptr)
15 {
16 stack.push(ptr);
17 ptr=ptr->lchild;
18 }
19
20 if (stack.isEmpty())
21 {
22 break;
23 }
24 ptr=stack.Top();
25 stack.pop();
26 count++;
27
28 ptr=ptr->rchild;
29 }
30 }
31
32 return count;
33 }
3.交换左右子树
交换左右子树
1 //交换左右子树
2 template<class T> void tree<T>::swap_tree()
3 {
4 swap(this->root);
5 }
6
7 template<class T> void tree<T>::swap(tree_node<T> *p)
8 {
9 if (p)
10 {
11 tree_node<T> *temp;
12 temp=p->lchild;
13 p->lchild=p->rchild;
14 p->rchild=temp;
15 swap(p->lchild);
16 swap(p->rchild);
17 }
18 }
4.获得树层数
树层数
1 //获得树层数
2 template<class T> int tree<T>::depth()
3 {
4 return get_depth(root);
5 }
6
7 template<class T> int tree<T>::get_depth(tree_node<T> *p)
8 {
9 if(p)
10 {
11 int left_depth=get_depth(p->lchild);
12 int rigth_depth=get_depth(p->rchild);
13
14 if (left_depth<=rigth_depth)
15 return rigth_depth+1;
16 else
17 return left_depth+1;
18 }
19 else
20 return 0; //空树
21 }

浙公网安备 33010602011771号