天天看點

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].

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

非遞歸:

/**
 * 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> v;
        const int max_node = ;
        TreeNode *arr[max_node];
        int top = ;
        if (root != NULL)
            arr[top++] = root;

        while (top > ) {
            root = arr[--top];

            v.push_back(root->val);
            //cout << "top: " << top << endl;
            //cout << "visit: " << root->val << endl;           
            if (root->right)
                arr[top++] = root->right;
            if (root->left)
                arr[top++] = root->left;

        }
        return v;
    }
};