Leetcode: Binary Tree Preorder Traversal
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, cocould you do it iteratively?
An iterative method instead of recursion is required. First, we will introduce the differences between iteration and Recursion:
Recursion: the so-called recursion, in short, refers to the application itself calling itself to achieve query and access to the hierarchical data structure.
Iteration: an iteration is an activity that repeats the feedback process. Its purpose is usually to approach the desired goal or result. Each iteration is called an "iteration", and the result of each iteration is used as the initial value of the next iteration.
Differences between iteration and Recursion:
// The following is an example of a Fibonacci sequence: // -------------------------------------- // 1. iteration Method: public class Fab_iterate {public static void main (String [] args) {System. out. println ("Result:" + Fab (8); // calculates the number of the eighth position} public static long Fab (int index) // Fibonacci series {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 ++) // iteration evaluate {f3 = f1 + f2; f1 = f2; f2 = f3 ;} return f3 ;}}// 2. recursive Method: public class Fab_recursion {public static void main (String [] args) {System. out. println ("Result:" + fab (8); // calculates the number of the eighth position} public static long fab (int index) // Fibonacci series {if (index = 1 | index = 2) {return 1;} else {return fab (index-1) + fab (index-2 ); // recursive evaluation }}}
Solution: first, when the root node is not empty, the root node is pushed into the stack and then iterated: When the stack is not empty, the top element of the stack is pushed out of the stack, save the value corresponding to the element to the value. Determine whether the right and left nodes of the node are empty. If not, the node is pushed to the stack in turn. If the stack is not empty, continue iteration.
Implementation Code:
/** * 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; }};