二叉树遍历
深度遍历 非递归:
1 void dfs(TreeNode*root) 2 { 3 if (root == NULL) return; 4 stack<TreeNode*> stackNode; 5 printf("%d", root->data); 6 7 stackNode.push(root); 8 TreeNode * node = nullptr; 9 10 while (!stackNode.empty()) 11 { 12 node = stackNode.top(); 13 stackNode.pop(); 14 15 if (node->right) 16 stackNode.push(node->right); 17 if (node->left) 18 stackNode.push(node->left); 19 } 20 21 }
广度优先:
1 //广度优先遍历 2 void breadthFirstSearch(Tree root){ 3 queue<Node *> nodeQueue; //使用C++的STL标准模板库 4 nodeQueue.push(root); 5 Node *node; 6 while(!nodeQueue.empty()){ 7 node = nodeQueue.front(); 8 nodeQueue.pop(); 9 printf(format, node->data); 10 if(node->lchild){ 11 nodeQueue.push(node->lchild); //先将左子树入队 12 } 13 if(node->rchild){ 14 nodeQueue.push(node->rchild); //再将右子树入队 15 } 16 } 17 }
posted on 2021-03-09 18:02 Ultraman_X 阅读(34) 评论(0) 收藏 举报