Binary Tree Preorder Traversal【144】

Datetime:2016-08-23 01:22:35          Topic: LeetCode           Share

144. Binary Tree Preorder Traversal

My Submissions

Total Accepted:  100308 Total Submissions:  262975 Difficulty:  Medium

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?

Subscribe to see which companies asked this question

Hide Tags
Tree   Stack

第一种简单做法:递归(前序式)

/**
 * 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){
            result.push_back(root->val);
            preorderTraversal(root->left);
            preorderTraversal(root->right);
        }
        return result;
    }
private:
    vector<int> result;
};




About List