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<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
原文地址:http://blog.csdn.net/wolongdede/article/details/43717199