Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values.

Example

Given:

    1
   / \
  2   3
 / \
4   5

return [1,2,4,5,3].

class Solution {  
public:  
    vector<int> preorderTraversal(TreeNode* root) {  
        vector<int> res;  
        if(root==NULL)
            return res;
        stack<TreeNode*> s;  
        s.push(root);  
        while(!s.empty()){  
            TreeNode *t=s.top();  
            s.pop();  
            v.push_back(t->val);  
            if(t->right)    //因为栈是先进后出,所以先放入右结点  
                s.push(t->right);  
            if(t->left)  
                s.push(t->left);  
        }  
        return res;  
    }  
};  


猜你喜欢

转载自blog.csdn.net/vanturman/article/details/79780269