Given a binary tree, return the inorder traversal of its nodes' values.
Example
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].
解题思路:
递归。与前序遍历代码几乎相同,仅仅是调整了顺序。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: A Tree
* @return: Inorder in ArrayList which contains node values.
*/
vector<int> result;
vector<int> inorderTraversal(TreeNode * root)
{
// write your code here
if(root == NULL) return result;
if(root->left != NULL)
result = inorderTraversal(root->left);
result.push_back(root->val);
if(root->right != NULL)
result = inorderTraversal(root->right);
return result;
}
};
本文介绍了一种使用递归方法实现二叉树中序遍历的算法,并提供了具体的C++实现代码。通过调整递归调用的顺序,可以有效地获取到节点值的中序遍历序列。
1824

被折叠的 条评论
为什么被折叠?



