Binary Tree Preorder Traversal

Description

Given a binary tree, return the preorder traversal of its nodes' values.

Example
Given:
    1
   / \
  2   3
 / \
4   5
return [1,2,4,5,3].

Challenge
Can you do it without recursion?

Lintcode_ladder

Method

  1. x
  2. x

Example

  1. Recursion Version
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: Preorder in vector which contains node values.
     */
    vector<int> preorderTraversal(TreeNode *root) {
        // write your code here
        vector<int> result;
        helper(root, result);
        return result;
    }
private:
    void helper(TreeNode* root, vector<int>& result){
        if (!root) {
            return;
        }
        result.push_back(root->val);
        helper(root->left, result);
        helper(root->right, result);
        return;
    }
};

Similar problems

x

Tags

x

results matching ""

    No results matching ""