您的位置:首页 > 编程语言

leetcode OJ -Binary Tree Preorder Traversal(2014.1.20)

2014-04-19 23:13 387 查看
递归:

/**
 * 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 preorder(TreeNode *root,vector<int> &path)  
    {
        if(root!=NULL)
        {
            path.push_back(root->val);
            preorder(root->left,path);
            preorder(root->right,path);
        }
    }
    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> path;
        preorder(root,path);
        return path;
    }
};

非递归 :

/**
 * 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> preorderTraversal(TreeNode *root) {
        vector<int> path;
        stack<TreeNode*> stk;
        if(root==NULL) return path;
        stk.push(root);
        TreeNode *cur=NULL;
        while(!stk.empty())
        {
            cur=stk.top();
            path.push_back(cur->val);
            stk.pop();
            if(cur->right!=NULL){
                stk.push(cur->right);
                cur->right==NULL;
            } 
            if(cur->left!=NULL){
                stk.push(cur->left);
                cur->left=NULL;
            }
        }
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 编程