leetcode94 - Binary Tree Inorder Traversal - medium
Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
Inorder: root in the middle
先一路traverse到最左边的leaf node,一路上把经过的node都push进stack。最先pop出来的就是起点,也相当于一个夹在中间的root(它的left child是null),所以去到它的right child,再如此循环。因为不涉及修改node,直接拿root来traverse就行,stack里都是相对来说的left node。
实现:
class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> res; if (!root) return res; stack<TreeNode*> st; while (!st.empty() || root){ while (root){ st.push(root); root = root->left; } root = st.top(); st.pop(); res.push_back(root->val); root = root->right; } return res; } };

浙公网安备 33010602011771号