Binary Tree Preorder Traversal (leetcode 144)

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;
    }
};
阅读更多
文章标签: 算法
个人分类: 算法、技术
上一篇Longest Substring Without Repeating Characters(leetcode 3)
下一篇Lowest Common Ancestor of a Binary Search Tree (235)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭