leetcode OJ -Binary Tree Preorder Traversal(2014.1.20)

来源:互联网 发布:锦绣未央网络首播量 编辑:程序博客网 时间:2024/06/14 03:33
递归:
/**
 * 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;
            }
        }
    }
};
0 0