[leetcode-144]Binary Tree Preorder Traversal(c++)

来源:互联网 发布:关于网络直播的议论文 编辑:程序博客网 时间:2024/05/13 00:44

问题描述:
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?

分析:树的先序遍历,不让使用递归,那就借用栈的结构,因为先序遍历,是先左后右。所以压栈时是先右再左。

代码如下:0ms

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