- 前序遍历:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: vector<int>result; public: //方法一: /*vector<int> preorderTraversal(TreeNode* root) { if(root==NULL) return result; stack<TreeNode*>stk; stk.push(root); while(stk.size())//当当前栈不为空的时候,先弹出栈顶。压入先右后左,然后循环; { root=stk.top(); result.push_back(root->val); stk.pop(); if(root->right) stk.push(root->right); if(root->left) stk.push(root->left); } return result; }*/ //方法二: vector<int> preorderTraversal(TreeNode* root) { if(root==NULL) return result; stack<TreeNode*>stk; while(root||stk.size()) { while(root)//往左一直遍历并打印,并且将当前的点入栈; { result.push_back(root->val); stk.push(root); root=root->left; } if(stk.size())//如果往左走到头的话,当前结点为栈顶元素,弹出栈顶,往右走;那么开始往右走;继续往左走;回到上一步中了; { root=stk.top(); stk.pop(); root=root->right; } } return result; } };
- 二叉树的中序遍历:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private:vector<int>result; public: vector<int> inorderTraversal(TreeNode* root) { if(root==NULL) return result; stack<TreeNode*>stk; while(root||stk.size()) { while(root)//一直往左遍历,找到最左,并且将每一个结点压入栈; { stk.push(root); root=root->left; } if(stk.size())//找到最左的点; { root=stk.top();//最左的点为栈顶元素; result.push_back(root->val);//保存最左的点的值; stk.pop();//弹出栈顶元素,出栈操作; root=root->right;//然后往右遍历,再返回上一步继续往左查找; } } return result; } };
- 后序遍历:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: //方法一:按照中右左的前序遍历方式;然后反转; /*vctor<int> postorderTraversal(TreeNode* root) { if(root==NULL) return result; stack<TreeNode*>stk; while(root||stk.size()) { while(root) { result.push_back(root->val);//往右遍历保存每一个结点; stk.push(root);//结点入栈; root=root->right;//一直往右走;走到最最右结点;; } if(stk.size()) { root=stk.top();//当前根节点为栈顶元素,也就是最右结点,没有最右的时候 找其左子树;并且在继续返回循环,再找右子树; //result.push_back(root->val); stk.pop(); root=root->left; } } reverse(result.begin(),result.end()); return result; } */ vector<int> postorderTraversal(TreeNode* root) { if(root==NULL) return result; stack<TreeNode*>stk; stk.push(root);//先将根节点压入;在中右左的方式遍历; while(stk.size()) { root=stk.top();//弹出栈顶; result.push_back(root->val); stk.pop();//每次弹出一个,压入两个;每次弹出的数据,把其子树压入。按照左右的顺序压入,弹出的时候才是右左; if(root->left) stk.push(root->left); if(root->right) stk.push(root->right); } reverse(result.begin(),result.end()); return result; } private:vector<int>result; };
二叉树的三种遍历方式的 非递归遍历使用栈;
最新推荐文章于 2020-10-16 00:26:52 发布