力扣-94-二叉树的中序遍历
题目:传送门
方法一、递归
中序遍历:先遍历左子树,在遍历根节点,最后遍历右子树。比较经典的方法是递归。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include <vector> using namespace std; class Solution { public: void dfs(vector<int>& res, TreeNode* root){ if(root == NULL) return ; dfs(res, root->left); res.push_back(root->val); dfs(res, root->right); } vector<int> inorderTraversal(TreeNode* root) { vector<int> result; dfs(result, root); 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) {} * }; */ /*方法二、使用栈的中序遍历*/ #include <vector> #include <stack> using namespace std; class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> res; stack<TreeNode* > Stack; TreeNode* curr = root; while(curr != NULL || !Stack.empty()){ while(curr != NULL) {//找左子树,并压入堆栈 Stack.push(curr); curr = curr->left; } curr = Stack.top();//top()返回栈顶元素,但是不删除; Stack.pop();//pop()删除栈顶元素,但是不返回 res.push_back(curr->val); curr = curr->right; } return res; } };
作者:Ryanjie
出处:http://www.cnblogs.com/ryanjan/
本文版权归作者和博客园所有,欢迎转载。转载请在留言板处留言给我,且在文章标明原文链接,谢谢!
如果您觉得本篇博文对您有所收获,觉得我还算用心,请点击右下角的 [推荐],谢谢!