您的位置:首页 > 其它

Binary Tree Inorder Traversal 二叉树的中序遍历

2015-04-24 21:24 363 查看


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?

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    /*递归版
    vector<int> inorderTraversal(TreeNode *root) {
        
        vector<int> res;
        solve(root,res);
        return res;
    }
    
    void solve(TreeNode *root,vector<int> &res)
    {
        if(root!=NULL)
        {
            solve(root->left,res);
            res.push_back(root->val);
            solve(root->right,res);
        }
    }
    */
    
    vector<int> inorderTraversal(TreeNode *root) {
        
        vector<int> res;
        stack<TreeNode* > s;  
        TreeNode* current=root;  
      
        while(!s.empty()||current!=NULL)   
        {  
            if(current!=NULL)   
            {  
                s.push(current);// 根先进,在继续左孩子,直到为空   
                current=current->left;  
            }  
            else   
            {  
                current=s.top();  
                s.pop();  
                res.push_back(current->val);// 根   
                current=current->right;//右   
            }  
        }  
        return res;
    }
    
   
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐