144. Binary Tree Preorder Traversal

来源:互联网 发布:java多态的机制是什么 编辑:程序博客网 时间:2024/06/06 01:28

题目描述【Leetcode】

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 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>re;        if(!root) return re;        stack<TreeNode*>nodes;        nodes.push(root);        while(!nodes.empty()){            TreeNode* temp = nodes.top();            re.push_back(temp->val);            nodes.pop();            if(temp->right) nodes.push(temp->right);            if(temp->left) nodes.push(temp->left);        }        return re;    }};
原创粉丝点击