144.Binary Tree Preorder Traversal

思路:
  • 递归
/**
 * Definition for a binary tree node.
 * 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> res;
        Tree(root,res);
        return res;
    }
    void Tree(TreeNode* root,vector<int>& res){
        if(root){
            res.push_back(root->val);
            Tree(root->left,res);
            Tree(root->right,res);
        }
    }
};
  • 利用栈进行遍历。
/**
 * Definition for a binary tree node.
 * 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> res;
        stack<TreeNode*> tmp;
        if(root == NULL) return {};
        tmp.push(root);
        while(!tmp.empty()){
            TreeNode *p = tmp.top();
            res.push_back(p->val);
            tmp.pop();
            if(p->right)tmp.push(p->right);
            if(p->left)tmp.push(p->left);
        }
        return res;
    }
};
  • 直接遍历,以后写。。
posted @ 2017-06-15 11:06  UniMilky  阅读(98)  评论(0编辑  收藏  举报