树的遍历(先序)

  1. 先序:
    解法一:递归:
/**
 * 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 preorderTraversal(TreeNode* root) {
        vector  result;
        traversal(root, result);
        return result;
    }
private:
    void traversal(TreeNode * root, vector &ret){
        if(root != NULL){
            ret.push_back(root->val);
            traversal(root->left, ret);
            traversal(root->right, ret);
        }

    }
};

解法二:Divide and Conquer

/**
 * 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 preorderTraversal(TreeNode* root) {
        vector result;
        if(root != NULL){
            vector left =  preorderTraversal(root->left);
            vector right =  preorderTraversal(root->right);
            
            result.push_back(root->val);
            result.insert(result.end(), left.begin(), left.end());
            result.insert(result.end(), right.begin(), right.end());
            
        }
        return result;
    }
};

解法三:迭代:
借助栈,先压入右节点,再压入左节点。

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

你可能感兴趣的:(树的遍历(先序))