Binary Tree Preorder Traversal

Binary Tree Preorder Traversal

 Total Accepted: 4309 Total Submissions: 12898My Submissions

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:
    void preorder(TreeNode *root, vector<int> &temp)
    {
        if(!root)
            return ;
        temp.push_back(root->val);
        preorder(root->left,temp);
        preorder(root->right,temp);
    }
    vector<int> preorderTraversal(TreeNode *root) 
    {
        vector<int> result;
        preorder(root, result);
        return result;
    }
};



每天早上叫醒你的不是闹钟,而是心中的梦~
原文地址:https://www.cnblogs.com/vintion/p/4116990.html