给定一个二叉树的根节点 root ,返回它的 中序 遍历。
开辟一个栈存节点,一个数组保存节点的值
判断节点是否为空,或者栈是否为空
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> inorderTraversal(TreeNode* root) { stack<TreeNode*> s; vector<int> result; TreeNode *cur = root; while(cur!=NULL || !s.empty()) { if(cur!=NULL) //将一直遍历到最左边 { s.push(cur); cur = cur->left; } else { // 把点Put cur = s.top(); s.pop(); //将数据弹出了 result.push_back(cur->val); cur = cur->right; } } return result; } };