Binary Tree Inorder Traversal (二叉树的中序遍历)
题目描述:
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?
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
思路:
根据中序遍历原则:左根右的原则,运用递归来遍历,当然也可以写非递归版本,需要用到栈,以后我再附上非递归的代码。
以下代码是我在牛客网oj环境下编译测试通过的:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
vector<int> s;//定义一个容器
public:
vector<int> inorderTraversal(TreeNode *root) {
if(root==NULL)
{
return s;
}
inorderTraversal(root->left);
s.push_back(root->val);
inorderTraversal(root->right);
return s;
}
};