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].
Note: Recursive solution is trivial, could you do it iteratively?
大致題意
給出中序遍歷
題解
問題型別:資料結構-樹
沒什麼好說的,中序遍歷優先遍歷左節點,然後輸出中間節點的 val,最後遍歷右節點
程式碼如下
/**
* 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> inorderTraversal(TreeNode* root) {
vector<int> result;
if (root != NULL) this->run(root, result);
return result;
}
void run(TreeNode * root, vector<int> & result) {
if (root->left != NULL) this->run(root->left, result);
result.push_back(root->val);
if (root->right != NULL) this->run(root->right, result);
}
};