广义表方式创建二叉树及二叉树输出广义表(C++)

  • 二叉树结构定义

    template <typename DataType> struct BTNode {
    	DataType value;
    	struct BTNode *lchild;
    	struct BTNode *rchild;
    
    	explicit BTNode(DataType x) : value(x), lchild(NULL), rchild(NULL) {}
    };

    数据类型用template模板定义,创建一个树节点可以写为:

    BTNode<DataType> *p = new BTNode(x);
  • 广义表建立二叉树

    // Translate the string to a BTree
    // sample:A(B(,G),C(D(F),E))
    // output:
    //			A
    //		  /	  \
    //		 B		C
    //		  \	  /	  \
    //		   G D	   E
    //		    /
    //		   F
    BTNode<char>* StrToBTree(const char *str, BTNode<char> *&T) {
    	if (!str) return NULL;
    	std::stack <BTNode<char>*> st;
    	int flag = -1;
    	BTNode<char> *p = NULL;
    
    	if (T) {
    		free(T); T = NULL;
    	}
    	for (int i = 0; str[i] != '\0'; i++) {
    		switch(str[i]) {
    		case '(':
    			if (p) {
    				flag = 0;// start_left_child
    				st.push(p);
    				p = NULL;
    			}
    			break;
    		case ')':
    			st.pop();
    			break;
    		case ',':
    			flag = 1; // start_right_child
    			break;
    		default:
    			p = new BTNode<char>(str[i]);
    			if (!T) T = p; // save the original root
    			else {
    				switch (flag) {    
                        case 0:
    						st.top()->lchild = (BTNode*)p;
                            break;
                        case 1:
                            st.top()->rchild = (BTNode*)p;
                            break;
                        default:
                            break;
                    }
    			}
    			break;
    		}
    	}
    
    	return T;
    }
  • 二叉树输出广义表

    // Translate the BTree to a string
    // sample:
    //			A
    //		  /	  \
    //		 B		C
    //		  \	  /	  \
    //		   G D	   E
    //		    /
    //		   F
    // output:A(B(,G),C(D(F),E))
    char* BTreeToStr(BTNode<char> *T, char *str) {
    	if (!str) return NULL;
    	if (!T) return NULL;
    	static int i = 0;
    
    	str[i++] = T->value;
    	if (T->lchild || T->rchild) 
    		str[i++] = '(';
    	BTreeToStr((BTNode<char>*)T->lchild, str);
    	if (T->rchild) 
    		str[i++] = ',';
    	BTreeToStr((BTNode<char>*)T->rchild, str);
    	if (T->lchild || T->rchild) 
    		str[i++] = ')';
    	
    	str[i] = 0;
    	return str;
    }

     

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值