Leetcode:Binary Tree Preorder Traversal

Given a binary tree, return thepreordertraversal 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?

题目要求用迭代的方法,而不是递归。首先介绍下迭代和递归的区别:

递归:所谓递归,简而言之就是应用程序自身调用自身,以实现层次数据结构的查询和访问。

迭代:迭代是重复反馈过程的活动,其目的通常是为了逼近所需目标或结果。每一次对过程的重复称为一次”迭代”,而每一次迭代得到的结果会作为下一次迭代的初始值。

迭代与递归的区别:

//以下以一个斐波那契数列的例子说明://———————————-//1.迭代方法:public class Fab_iterate {public static void main(String[] args) { System.out.println("结果是:"+Fab(8)); //求第八个位置的数 } public static long Fab(int index) //斐波那契数列 {if(index == 1 || index == 2){return 1;}else{long f1 = 1L;long f2 = 1L;long f3 = 0;for(int i = 0;i < index-2;i ++) //迭代求值{f3 = f1 + f2;f1 = f2;f2 = f3;}return f3;} }}//2.递归方法:public class Fab_recursion { public static void main(String[] args) { System.out.println("结果是:"+fab(8)); //求第八个位置的数 } public static long fab(int index) //斐波那契数列 {if(index == 1 || index == 2){return 1;}else{return fab(index-1)+fab(index-2); //递归求值}}}解题思路:首先当根节点不为空时,把根节点压入栈中,然后进行迭代:当栈不为空时,把栈顶元素出栈,,并把该元素对应的数值保存到数值中。判断该节点的右节点和左节点是否为空,如果不为空,则依次压入栈中。若栈不为空,继续进行迭代。

实现代码:

/** * Definition for binary tree * 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) {if (root==NULL) {return vector<int>();}vector<int> result;stack<TreeNode *> treeStack;treeStack.push(root);while (!treeStack.empty()) {TreeNode *temp = treeStack.top();result.push_back(temp->val);treeStack.pop();if (temp->right!=NULL) {treeStack.push(temp->right);}if (temp->left!=NULL) {treeStack.push(temp->left);}}return result;}};

用最多的梦面对未来

Leetcode:Binary Tree Preorder Traversal

相关文章:

你感兴趣的文章:

标签云: