LeetCode 144 Binary Tree Preorder Traversal(二叉树的前序遍历)+(二叉树、迭代)

来源:互联网 发布:linux while循环 编辑:程序博客网 时间:2024/05/14 07:02

翻译

给定一个二叉树,返回其前序遍历的节点的值。例如:给定二叉树为 {1#, 2, 3}   1    \     2    /   3返回 [1, 2, 3]备注:用递归是微不足道的,你可以用迭代来完成它吗?

原文

Given a binary tree, return the preorder traversal of its nodes' values.For example:Given binary tree {1,#,2,3},   1    \     2    /   3return [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> v;    vector<int> preorderTraversal(TreeNode* root) {        if (root != NULL) {            v.push_back(root->val);            preorderTraversal(root->left);            preorderTraversal(root->right);        }        return v;    }};

紧接着,咱来写迭代的……

/*** 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> result;        stack<TreeNode*> tempStack;        while (!tempStack.empty() || root != NULL) {            if (root != NULL) {                result.push_back(root->val);                tempStack.push(root);                root = root->left;            }            else {                root = tempStack.top();                tempStack.pop();                root = root->right;            }        }        return result;    }};

另有两道类似的题目:

LeetCode 94 Binary Tree Inorder Traversal(二叉树的中序遍历)+(二叉树、迭代)
LeetCode 145 Binary Tree Postorder Traversal(二叉树的后续遍历)+(二叉树、迭代)

3 0
原创粉丝点击