Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> inorderTraversal(TreeNode *root) { 13 vector<int> result; 14 stack<TreeNode *> s; 15 TreeNode *p = root; 16 17 while (p != nullptr || !s.empty()) { 18 if (p != nullptr) { 19 s.push(p); 20 p = p->left; 21 } else { 22 p = s.top(); 23 s.pop(); 24 result.push_back(p->val); 25 p = p->right; 26 } 27 } 28 29 return result; 30 } 31 };