Binary Tree Inorder Traversal
Q:Given a binary tree, return the inorder traversal of its nodes' values.
(1)迭代版本:
思路:用stack模仿递归的过程
对于任何结点p
1. 如果p的左孩子不为空,那么将p入栈,p置为左孩子,重复相同的处理
2. 如果p的左孩子为空,则取栈顶元素并进行出栈操作,然后将当前的P置为原栈顶结点的右孩子;重复相同的处理
3. 直至p为NULL或者栈为空,循环结束。
1 vector<int> inorderTraversal(TreeNode *root) { 2 // Start typing your C/C++ solution below 3 // DO NOT write int main() function 4 vector<int> result; 5 TreeNode *pIter = root; 6 7 stack<TreeNode*> s; 8 9 while(pIter!=NULL||!s.empty()) 10 { 11 while(pIter!=NULL) 12 { 13 s.push(pIter); 14 pIter = pIter->left; 15 } 16 17 if(!s.empty()) 18 { 19 pIter = s.top(); 20 s.pop(); 21 result.push_back(pIter->val); 22 pIter = pIter->right; 23 } 24 } 25 26 return result; 27 28 }
(2) 递归版本
void inorderTraversal(TreeNode *root, vector<int>&result)
{
    if(root!=NULL)
   {
       inorderTraversal(root->left,result);
       result.push_back(root->val);
       inorderTraversal(root->right,result);
   }  
}
                    
                
                
            
        
浙公网安备 33010602011771号