Given a binary tree, return the inordertraversal 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?
typedef char ElemType; typedef struct BiTreeNode { ElemType data; struct BiTreeNode *left; struct BiTreeNode *right; }BiTreeNode,*BiTree;
Binary Tree Inorder Traversal void InOrderBiTree(BiTree T){ if(T == NULL) return; InOrderBiTree(T->left); printf("%c",T->data); InOrderBiTree(T->right); }
以下方法可作参考,优先学习以下两种解法:
//recursion C++ Solution1: class Solution{ public: vector<int> inorderTraversal(TreeNode *root){ vector<int> res; inorder(root,res); return res; } void inorder(TreeNode *root, vector<int> &res){ if(!root) return; if(root->left) inorder(root->left,res); res.push_back(root->val); if(root->right) inorder(root->right,res); } }; //no recursion: class Solution{ public: vector<int> inorderTraversal(TreeNode *root){ vector<int> res; stack<TreeNode*> s; TreeNode *p = root; while(!s.empty() || p){ if(p){ s.push(p); p = p->left; } else{ TreeNode *t = s.top();s.pop(); res.push_back(t->val); p = t->right; } } return res; } };