今天寫經典的tree traversal - inorder
inorder: 左邊先拜訪,接著中間,最後右邊。
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
if(root == NULL)
return {};
stack<TreeNode*> s;
TreeNode* curr_node = root;
while( curr_node || !s.empty() ) {
if (curr_node) {
s.push(curr_node);
curr_node = curr_node->left;
}
else {
TreeNode *node = s.top();
s.pop();
ans.push_back(node->val);
curr_node = node->right;
}
}
return ans;
}
};
參考:
https://ithelp.ithome.com.tw/articles/10213280
https://shubo.io/iterative-binary-tree-traversal/