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?
題目要求用迭代的方法,而不是遞歸。首先介紹下迭代和遞歸的區別:
遞歸:所謂遞歸,簡而言之就是應用程序自身調用自身,以實現層次數據結構的查詢和訪問。
迭代:迭代是重復反饋過程的活動,其目的通常是為了逼近所需目標或結果。每一次對過程的重復稱為一次”迭代”,而每一次迭代得到的結果會作為下一次迭代的初始值。
迭代與遞歸的區別:
//以下以一個斐波那契數列的例子說明:
//----------------------------------
//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 preorderTraversal(TreeNode *root) {
if (root==NULL) {
return vector();
}
vector result;
stack 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;
}
};