Binary Tree Preorder Traversal (leetcode 144),preorderleetcode


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?

Show Tags
Show Similar Problems


可以递归,可以用栈

/**
 * 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> preorderTraversal(TreeNode* root) {
        if (root == NULL) {
            return vector<int>();
        }
        vector<int> a;
        a.push_back(root->val);
        vector<int> l = preorderTraversal(root->left);
        vector<int> r = preorderTraversal(root->right);
        a.insert(a.end(), l.begin(), l.end());
        a.insert(a.end(), r.begin(), r.end());
        return a;
    }
};

// 非递归

/**
 * 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> preorderTraversal(TreeNode* root) {
        vector<int> a;
        if (root == NULL) {
            return a;
        }
        stack<TreeNode*> s;
        s.push(root);
        while(!s.empty()) {
            TreeNode* r = s.top();
            s.pop();
            a.push_back(r->val);
            if (r->right != NULL) {
                s.push(r->right);
            }
            if (r->left != NULL) {
                s.push(r->left);
            }
        }
        return a;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关内容