力扣 题目94- 二叉树的中序遍历
作者:互联网
题目
题解
二叉树有点忘记了 专门去复习了 一遍 其实就是 左中右
一看用递归或者栈吧
栈比较简单一些 我们直接不断向左移动 碰到空就向栈顶的右走即可
代码
1 #include<iostream> 2 #include<vector> 3 #include<stack> 4 using namespace std; 5 6 struct TreeNode { 7 int val; 8 TreeNode *left; 9 TreeNode *right; 10 TreeNode() : val(0), left(nullptr), right(nullptr) {} 11 TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 12 TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 13 }; 14 15 class Solution { 16 public: 17 vector<int> inorderTraversal(TreeNode* root) { 18 vector<int> result; 19 stack<TreeNode*> ergodic; 20 while (root != nullptr || !ergodic.empty()) { 21 if (root != nullptr) { 22 ergodic.push(root); 23 root = root->left; 24 } 25 else 26 { 27 result.push_back(ergodic.top()->val); 28 root = ergodic.top()->right; 29 ergodic.pop(); 30 } 31 } 32 return result; 33 } 34 }; 35 36 37 38 int main() { 39 Solution sol; 40 //懒得写遍历了 41 TreeNode* root7 = new TreeNode(7); 42 TreeNode* root6 = new TreeNode(6); 43 TreeNode* root5 = new TreeNode(5); 44 TreeNode* root4 = new TreeNode(4); 45 TreeNode* root3 = new TreeNode(3, root6, root7); 46 TreeNode* root2 = new TreeNode(2, root4, root5); 47 TreeNode* root1=new TreeNode(1, root2, root3); 48 vector<int> result=sol.inorderTraversal(root1); 49 for (int i = 0; i < result.size(); i++) { 50 cout << result[i] << endl; 51 } 52 }View Code
标签:right,TreeNode,中序,nullptr,力扣,二叉树,new,root,left 来源: https://www.cnblogs.com/zx469321142/p/16491458.html