题目描述:给出一棵二叉树,返回其中序遍历
样例:
给出二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [1,3,2]
.
做题思路:递归算法,先遍历左子树,在看根节点,再遍历右子树,遍历后的结点放进数组中,返回数组。
关键代码:class Solution {
/**
* @param root: The root of binary tree.
* @return: Inorder in vector which contains node values.
*/
public:
std::vector<int> w;
vector<int> inorderTraversal(TreeNode *root) {
// write your code here
if(root==NULL) return w;
else { inorderTraversal(root->left);
w.push_back(root->val);
inorderTraversal(root->right);
}
return w;
}
};
做题感想:和先根遍历一样,只不过把存入数组的语句位置变了。