题目:给出一棵二叉树,返回其中序遍历
样例
给出二叉树 {1,#,2,3}
,
1 2 / 3
返回 [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> inorderTraversal(TreeNode * root) { // write your code here vector<int> re; if(root!=NULL) inorder(root,re); return re; } void inorder(TreeNode *node,vector<int> &re) { if(node==NULL) return; if(node->left!=NULL) inorder(node->left,re); re.push_back(node->val); if(node->right!=NULL) inorder(node->right,re); } };