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,3}
1 \ 2 / 3返回 [1,3,2]
注意:递归不重要,重要的是迭代←_←
我会说这道题就是把前序遍历的两句话换一下就行了么。。。
/**
* 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;
if(!root) return vec;
traval(root,vec);
return vec;
}
void traval(TreeNode* root,vector<int>& vec){
if(root->left) traval(root->left,vec);
vec.push_back(root->val);
if(root->right) traval(root->right,vec);
}
};
好久没刷LeetCode了啊。。。最近都没什么时间,又是物联网大赛又是考研的。。。只能趁中午的休息时间看看(还不一定会做。。。)