[leetcode_144]Binary Tree Preorder Traversal

哎哟我擦。用递归让我 AC 了还不算我过,题目前面没打勾,对我这种有强迫症的人来说,好痛苦。回头想想别的办法。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {  
public:  
    vector<int> ans;  
    vector<int> preorderTraversal(TreeNode *root) {  
        // IMPORTANT: Please reset any member data you declared, as  
        // the same Solution instance will be reused for each test case.  
        ans.clear();  
        fun(root);  
        return ans;  
    }  
    void fun(TreeNode *root)  {  
        if (root != NULL) {  
            ans.push_back(root->val);  
            if (root->left != NULL)  
                fun(root->left);  
            if (root->right != NULL)  
                fun(root->right);  
        }  
    }  
};
Licensed under CC BY-NC-SA 4.0