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?
中序遍历二叉树,递归遍历当然很容易,题目还要求不用递归,下面给出两种方法:
递归:
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 if(!root) return ret; 14 tranverse(root); 15 return ret; 16 } 17 18 void tranverse(TreeNode * root) 19 { 20 if(!root) return; 21 tranverse(root->left); 22 ret.push_back(root->val); 23 tranverse(root->right); 24 } 25 private: 26 vector<int> ret; 27 };
迭代:
1 class Solution { 2 public: 3 vector<int> inorderTraversal(TreeNode* root) { 4 vector<int> ret; 5 if(!root) return ret; 6 map<TreeNode *, bool> m; 7 stack<TreeNode *> s; 8 s.push(root); 9 while(!s.empty()){ 10 TreeNode * t = s.top(); 11 if(t->left && !m[t->left]){ 12 m[t->left] = true; 13 s.push(t->left); 14 t = t->left; 15 continue; 16 } 17 ret.push_back(t->val); 18 s.pop(); 19 if(t->right && !m[t->right]){ 20 m[t->right] = true; 21 s.push(t->right); 22 t = t->right; 23 } 24 } 25 return ret; 26 } 27 };
时间: 2024-10-07 08:43:19