七月流火季节,小生独上数据结构算法山修炼内功,以防日后遇武林高手无法抵御 ... ...

     今日Mark Allen Weiss师父传授的是 木遁-‘树界’降临 ... ...

                          ------------------  Switch --------------------

     初级篇

     简介下如何运用栈创建一个简单的二叉树。以建立表达式树为例。

     程序逻辑比较清晰,对于一个后缀表达式,遇数字开辟树结点,入栈。遇操作符,弹出栈顶两元素,作为开辟树结点的参数,后入栈。

     小小的难点在于DFS遍历树的递归运用。

     e.g.   2 3 + 4 5 6 + * *   生成的树如图:

   

       代码演示

  

 1 // 简单二叉树的实现.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <stack>
 6 #include <iostream>
 7 #include <cctype>
 8 
 9 //基于后缀表达式构建二叉树
10 template <typename Object>
11 class SimpleBinaryTree
12 {
13 private:
14     struct  _BinaryNode
15     {
16         Object x;
17         _BinaryNode* left;
18         _BinaryNode* right;
19         _BinaryNode(const Object _x = Object(), _BinaryNode* _le = NULL, _BinaryNode* _ri = NULL)
20             :x(_x), left(_le), right(_ri) {}
21     };
22 public:
23     SimpleBinaryTree(){}
24     void createBt(const std::string& postfixExp)
25     {
26         std::stack<_BinaryNode*> sta;
27         for (int i = 0; i != postfixExp.size(); i++)
28         { 
29             if (postfixExp[i] == ' ') continue;
30             else if (isdigit(postfixExp[i])) sta.push(new _BinaryNode(postfixExp[i]));
31             else // 是操作符
32             {
33                 if (!sta.empty())
34                 {
35                     _BinaryNode* b1 = sta.top();
36                     sta.pop();
37 
38                     if (!sta.empty())
39                     {
40                         _BinaryNode* b2 = sta.top();
41                         sta.pop();
42                         sta.push(new _BinaryNode(postfixExp[i], b1, b2));
43                     }
44                 }
45             }
46 
47         }
48         if (!sta.empty())
49         {
50             root = sta.top();
51             sta.pop();
52         }
53     }
54     _BinaryNode* getRoot() { return root; }
55     void inorderTraversal() const
56     {
57         inorderTraversal(root);
58     }
59 private:
60     _BinaryNode* root; // 树的根
61     void inorderTraversal(_BinaryNode* index) const
62     {
63         if (index == NULL) return;
64         std::cout << "(";
65         inorderTraversal(index->left);
66         std::cout << index->x << " ";   // 中序遍历
67         inorderTraversal(index->right);
68         std::cout << ")";    // process( ...) 后序遍历
69     }
70 
71 };
72 
73 int main()
74 {
75     SimpleBinaryTree<char>* myBt = new SimpleBinaryTree<char>();
76     myBt->createBt("2 3 + 4 5 6 + * *");
77     myBt->inorderTraversal();
78     system("pause");
79     return 0;
80 }

 

        运行的结果 ((((6 )+ (5 ))* (4 ))* ((3 )+ (2 ))) 。虽然不太雅观,但是一个合法的中缀表达式。

        当然希望各路大神能将碍眼的 (X) 数字括号去掉。

 

    

posted on 2016-08-09 00:45  Elapsed_Time  阅读(139)  评论(0编辑  收藏  举报