Q:
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3]
,
1 \ 2 / 3
return [1,3,2]
.
A:
/**
* 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 {
public:
vector<int> result;
void dfs(TreeNode *p)
{
if(p->left!=NULL){
dfs(p->left);
}
result.push_back(p->val);
if(p->right!=NULL) {
dfs(p->right);
}
return;
}
vector<int> inorderTraversal(TreeNode* root) {
TreeNode * head = root;
result.clear();
if(head!=NULL){
dfs(head);
}
return result;
}
};