[LeetCode] Binary Tree Preorder Traversal [40]

来源:互联网 发布:淘宝介入有用吗 编辑:程序博客网 时间:2024/06/05 00:36

题目

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?

原题地址

解题思路

二叉树的前序遍历的非递归算法:

代码实现

    vector<int> preorderTraversal(TreeNode *root) {        vector<int> ret;        if (root == NULL)            return ret;        std::stack<TreeNode *> s;        s.push(root);        TreeNode *pNode = NULL;        while (!s.empty()) {            pNode = s.top();            s.pop();            ret.push_back(pNode->val);            if (pNode->right != NULL) {                s.push(pNode->right);            }            if (pNode->left != NULL) {                s.push(pNode->left);            }        }        return ret;    }
如果你觉得本篇对你有收获,请帮顶。
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
你可以搜索公众号:swalge 或者扫描下方二维码关注我

(转载文章请注明出处: http://blog.csdn.net/swagle/article/details/38322837 )

0 0
原创粉丝点击