144. Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [1,2,3].

递归实现:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
     vector<int>v;//这个必须放到外面,不能放到preorderTraversal的里面
    vector<int> preorderTraversal(TreeNode* root) {
        if(root!=NULL){
            v.push_back(root->val);
            preorderTraversal(root->left);
            preorderTraversal(root->right);
        }
        return v;
    }
};

非递归:

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int>v;
        stack<TreeNode*> s;
        if(root!=NULL)s.push(root);
        while(!s.empty()){
            TreeNode *t=s.top();
            s.pop();
            v.push_back(t->val);
            if(t->right)//因为栈是先进后出,所以先放入右结点
                s.push(t->right);
            if(t->left)
                s.push(t->left);
        }
        return v;
    }
};




你可能感兴趣的:(144. Binary Tree Preorder Traversal)