二叉樹的創建代碼==>C++ 創建和遍歷二叉樹
深度優先遍歷:是沿着樹的深度遍歷樹的節點,盡可能深的搜索樹的分支。
//深度優先遍歷二叉樹
void depthFirstSearch(Tree root){ stack<Node *> nodeStack; //使用C++的STL標准模板庫 nodeStack.push(root); Node *node; while(!nodeStack.empty()){ node = nodeStack.top(); printf(format, node->data); //遍歷根結點 nodeStack.pop(); if(node->rchild){ nodeStack.push(node->rchild); //先將右子樹壓棧 } if(node->lchild){ nodeStack.push(node->lchild); //再將左子樹壓棧 } } }
廣度優先遍歷:是從根節點開始,沿着樹的寬度遍歷樹的節點。如果所有節點均被訪問,則算法中止。
//廣度優先遍歷 void breadthFirstSearch(Tree root){ queue<Node *> nodeQueue; //使用C++的STL標准模板庫 nodeQueue.push(root); Node *node; while(!nodeQueue.empty()){ node = nodeQueue.front(); nodeQueue.pop(); printf(format, node->data); if(node->lchild){ nodeQueue.push(node->lchild); //先將左子樹入隊 } if(node->rchild){ nodeQueue.push(node->rchild); //再將右子樹入隊 } } }