leetcode-Binary Tree Inorder Traversal(2014.1.23)

遞歸方法:
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
 void inorder(TreeNode* p,vector<int> &path)
    {
        if(p!=NULL){
            inorder(p->left,path);
            path.push_back(p->val);
            inorder(p->right,path);
        }
    }
    vector<int> inorderTraversal(TreeNode *root) {
        vector<int> path;
        inorder(root,path);
        return path;
    }
};

非遞歸方法(迭代方法):前中後遍歷都使用棧,都可以將root先入,出棧序列有很多,不只是一種,要注意 這一點。
/**
 * 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) {
        stack<TreeNode*> stk;
        vector<int> path;
        TreeNode* cur=root;
        if(root==NULL) return path;
        while(!stk.empty()||cur!=NULL){
            while(cur){
                stk.push(cur);
                cur=cur->left;
            }
            cur=stk.top();
            path.push_back(cur->val);
            stk.pop();
            cur=cur->right;
        }
        return path;
    }
};
  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章