https://leetcode.com/problems/binary-tree-inorder-traversal/
class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> ans; stack<TreeNode*> todo;//定义一个栈,先入后出 while (root != nullptr || todo.empty() == false) { while (root) {//将左子树依次压入栈内 todo.push(root); root = root->left; } root = todo.top(); todo.pop(); ans.push_back(root->val); root = root->right; } return ans; } };
class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> ans; inorder(root, ans);//递归求解 return ans; } private: void inorder(TreeNode* root, vector<int>& ans) { if (root == nullptr) { return; } inorder(root->left, ans); ans.push_back(root->val); inorder(root->right, ans); } };
算法详解参考:https://zhuanlan.zhihu.com/p/101321696
class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> nodes; while (root) { if (root -> left) { TreeNode* pre = root -> left; while (pre -> right && pre -> right != root) { pre = pre -> right; } if (!pre -> right) { pre -> right = root; root = root -> left; } else { pre -> right = NULL; nodes.push_back(root -> val); root = root -> right; } } else { nodes.push_back(root -> val); root = root -> right; } } return nodes; } };
代码参考:https://leetcode.com/problems/binary-tree-inorder-traversal/discuss/31231/C%2B%2B-Iterative-Recursive-and-Morris