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, could you do it iteratively?

思路:

常规的递归调用PreOrder Traversal

代码:

递归版本

/**
 * 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> v;
    vector<int> preorderTraversal(TreeNode *root) {
        preorder(root);
        return v;
    }
    
    void preorder(TreeNode *root)
    {
        if(root !=NULL)
        {
            v.push_back(root->val);
            preorder(root->left);
            preorder(root->right);
        }
    }
};

非递归版本

/**
 * 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> result;
        stack<TreeNode*> node;
        
        if(root != NULL){
            node.push(root);
        }
        
        while(!node.empty()){
            TreeNode* p = node.top();
            node.pop();
            
            result.push_back(p->val);
            if(p->right != NULL){
                node.push(p->right);
            }
            if(p->left != NULL){
                node.push(p->left);
            }
        }
        
        return result;
    }
};

    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/17247727
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞