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?
Iteratively:
1 /** 2 * Definition for binary tree 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 TreeNode *sneil = NULL; 14 vector<int> rst; 15 if(root==NULL) 16 return rst; 17 18 stack<TreeNode*> istack; 19 istack.push(sneil); 20 while(!istack.empty()){ 21 while(root->left){ 22 istack.push(root); 23 root = root->left; 24 } 25 while(root!=NULL && root->right==NULL){ 26 rst.push_back(root->val); 27 root = istack.top(); 28 istack.pop(); 29 } 30 if(root==NULL) 31 break; 32 rst.push_back(root->val); 33 root = root->right; 34 } 35 return rst; 36 } 37 };
不使用stack的解法,明天再写。。
转载于:https://www.cnblogs.com/nnoth/p/3744111.html