如图所示的一颗二叉树:
上代码:
/** * 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*>st; vector<int>res; if(!root) return res; TreeNode* cur=root; while(cur){ st.push(cur); //从根节点开始一直往左边递 cur=cur->left; } while(!st.empty()){ cur=st.top(); //回溯(归) res.push_back(cur->val); st.pop(); if(cur->right){ //如果当前节点有右子节点,把它当成根节点,重复之前的步骤 cur=cur->right; while(cur){ st.push(cur); cur=cur->left; } } } return res; } };
小弟第一次写博客,如有疏漏请各位大神指出,谢谢!