[LeetCode]Binary Tree Inorder Traversal
Binary Tree Inorder Traversal
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?
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
中序遍历。左-根-右。迭代使用stack。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> inorderTraversal(TreeNode* root) { 13 vector<int> result; 14 if(!root) return result; 15 TreeNode* p; 16 stack<TreeNode*> mystack; 17 p = root; 18 while(!mystack.empty() || p) 19 { 20 if(p) 21 { 22 mystack.push(p); 23 p = p->left; 24 } 25 else 26 { 27 p = mystack.top(); 28 mystack.pop(); 29 result.push_back(p->val); 30 p = p->right; 31 } 32 } 33 return result; 34 } 35 };
递归的方法很统一。先序,中序,后续,只要修改遍历的顺序即可。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> inorderTraversal(TreeNode* root) { 13 vector<int> result; 14 traversal(root,result); 15 return result; 16 } 17 void traversal(TreeNode* root,vector<int>& ret) 18 { 19 if(root) 20 { 21 traversal(root->left,ret); 22 ret.push_back(root->val); 23 traversal(root->right,ret); 24 } 25 } 26 };