赞
踩
本篇博客介绍二叉树的先序遍历、中序遍历、后序遍历以及层次遍历
先序遍历:根节点---左子树---右子树
中序遍历:左子树---根节点---右子树
后序遍历:左子树---右子树---根节点
层次遍历:每一层按照从左到右依次遍历
先序遍历结果:1 2 4 5 7 8 3 6
中序遍历结果:4 2 7 5 8 1 3 6
后序遍历结果:4 7 8 5 2 6 3 1
层次遍历结果:1 2 3 4 5 6 7 8
首先,先序遍历的递归代码:
- vector<int> arr;
- vector<int> preorderTraversal(TreeNode* root)
- {
- if(root == NULL)
- {
- return arr;
- }
- arr.push_back(root->val);
- preorderTraversal(root->left);
- preorderTraversal(root->right);
- return arr;
- }
C++迭代的方式实现先序遍历:
- vector<int> preorderTraversal(TreeNode* root)
- {
- vector<int> arr;
- if(root == NULL)
- {
- return arr;
- }
- stack<TreeNode*> st;
- st.push(root);
- while(!st.empty())
- {
- root = st.top(); st.pop();
- arr.push_back(root->val);
- if(root->right != NULL)
- {
- st.push(root->right);
- }
- if(root->left != NULL)
- {
- st.push(root->left);
- }
- }
- return arr;
- }

中序遍历的递归代码:
- vector<int> arr;
- vector<int> inorderTraversal(TreeNode* root) {
- if(root == NULL)
- {
- return arr;
- }
- inorderTraversal(root->left);
- arr.push_back(root->val);
- inorderTraversal(root->right);
- return arr;
- }
C++迭代的方式实现中序遍历:
- vector<int> inorderTraversal(TreeNode* root) {
- vector<int> arr;
- stack<TreeNode*> st;
- while(root != NULL || !st.empty())
- {
- if(root != NULL)
- {
- st.push(root);
- root = root->left;
- }
- else
- {
- root = st.top(); st.pop();
- arr.push_back(root->val);
- root = root->right;
- }
- }
- return arr;
- }

C++递归的方式实现后序遍历:
- vector<int> arr;
- vector<int> postorderTraversal(TreeNode* root) {
- if(root == NULL)
- {
- return arr;
- }
- postorderTraversal(root->left);
- postorderTraversal(root->right);
- arr.push_back(root->val);
- return arr;
- }
C++迭代的方式实现后序遍历:
- vector<int> postorderTraversal(TreeNode* root) {
- vector<int> arr;
- if(root == NULL)
- {
- return arr;
- }
- stack<TreeNode*> st;
- TreeNode* tag = NULL;
- while(root != NULL || !st.empty())
- {
- while(root != NULL)
- {
- st.push(root);
- root = root->left;
- }
- root = st.top(); st.pop();
- if(root->right == NULL || root->right == tag)
- {
- arr.push_back(root->val);
- tag = root;
- root = NULL;
- }
- else
- {
- st.push(root);
- root = root->right;
- }
- }
- return arr;
- }

C++迭代的方式实现层次遍历:
- vector<vector<int>> levelOrder(TreeNode* root) {
- queue<TreeNode*> qu;
- vector<vector<int>> vec;
- qu.push(root);
- int depth = 0;
- while(!qu.empty())
- {
- vector<int> arr;
- int count = qu.size();
- while(count > 0)
- {
- TreeNode* pNode = qu.front(); qu.pop();
- if(pNode!=NULL)
- arr.push_back(pNode->val);
- if((pNode != NULL) && (pNode->left != NULL))
- {
- qu.push(pNode->left);
- }
- if((pNode != NULL) && (pNode->right != NULL))
- {
- qu.push(pNode->right);
- }
- count--;
- }
- if(root!=NULL)
- vec.push_back(arr);
- }
- return vec;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。