(二叉树 递归) leetcode94. Binary Tree Inorder Traversal

时间:2023-03-10 00:42:33
(二叉树 递归) leetcode94. Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
1
\
2
/
3 Output: [1,3,2]

Follow up: Recursive solution is trivial, could you do it iteratively?

---------------------------------------------------------------------------------------------------------------

leetcode 144. Binary Tree Preorder Traversal 几乎相似。题目要求我们尽量用迭代求解,不过,我不太会,所以用递归。

C++代码:

/**
* 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> vec;
inorder(root,vec);
return vec;
}
void inorder(TreeNode *root,vector<int> &vec){
if(!root) return;
inorder(root->left,vec);
vec.push_back(root->val);
inorder(root->right,vec);
}
};