二叉树中序非递归
- 从root开始,一直往左孩子走入栈,走到头
- 倒退回去到有右孩子的点重复上一个步骤,注意,这中间经过的栈扔出去的点,包括最后一个有右孩子的点都要存到ans里面
- 注意判断stack为空
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * 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 { vector<int>ans; public: vector<int> inorderTraversal(TreeNode* root) { stack<TreeNode*>tree; if(root==NULL) return ans; tree.push(root); while(!tree.empty()) { TreeNode*stacktop=tree.top(); while(stacktop->left!=NULL) { tree.push(stacktop->left); stacktop=tree.top(); } while(!tree.empty() && tree.top()->right==NULL) { stacktop=tree.top(); tree.pop(); ans.push_back(stacktop->val); } if(tree.empty()) return ans; stacktop=tree.top(); ans.push_back(stacktop->val); tree.pop(); tree.push(stacktop->right); } return ans; } };
时间才能证明一切,选好了就尽力去做吧!