Question: Given a binary tree, return the preorder traversal of its nodes 'values.
This is called the forward traversal of a binary tree. The recursive method is simple: the node is first followed by the Left subtree and then the right subtree. The iterative method can use stack storage to complete the traversal process.
Difference between Recursion and iteration: many problems are explained in the form of recursion, because it is clearer than non-recursive forms. However, iterations of these problems are often more efficient than recursive implementations, and the code may be slightly less readable. When a problem is complicated and difficult to implement in iterative form, the conciseness of Recursive Implementation can compensate for the runtime overhead it brings. When using recursion, you must consider the comparison between its benefits and its cost.
Code above ~
Recursive Method Python
# Definition for a binary tree node# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution: # @param root, a tree node # @return a list of integers def preorderTraversal(self, root): rs=[] if root!=None: rs.append(root.val) rs+=self.preorderTraversal(root.left)+self.preorderTraversal(root.right) return rs
Iterative Method C ++
/** * 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) { vector<int> rs; stack<TreeNode *> nstack; if (root==NULL) return rs; nstack.push(root); rs.push_back(root->val); TreeNode *next = root->left; while (next != NULL || !nstack.empty()) { while (next != NULL) { rs.push_back(next->val); nstack.push(next); next = next->left; } next = nstack.top(); nstack.pop(); next = next->right; } }};
Leetcode_num8_binary tree preorder traversal