算法模板二叉树

Posted Vincent丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法模板二叉树相关的知识,希望对你有一定的参考价值。

模板:

1.先序遍历三种方法

1)迭代:

class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: Preorder in vector which contains node values.
     */    
    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> res;
        stack<TreeNode*> stack;
        
        if (root == NULL) {
            return res;
        }
        
        stack.push(root);
        while (!stack.empty()) {
            TreeNode *node = stack.top();
            stack.pop();
            res.push_back(node->val);
            if (node->right != NULL) {
                stack.push(node->right);
            }
            if (node->left != NULL) {
                stack.push(node->left);
            }
        }
        
        return res;
    }
};

 

2)递归:

class Solution {
public:
    void traversal(TreeNode *root, vector<int>& res) {
        if (root == NULL) {
            return;
        }
        
        res.push_back(root->val);
        traversal(root->left, res);
        traversal(root->right, res);
    }
    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> res;
        traversal(root, res);
        
        return res;
    }
};

3)分治:

class Solution {
public:    
    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> res;
        if (root == NULL) {
            return res;
        }
        
        vector<int> left = preorderTraversal(root->left);
        vector<int> right = preorderTraversal(root->right);
        
        res.push_back(root->val);
        res.insert(res.end(), left.begin(), left.end());
        res.insert(res.end(), right.begin(), right.end());
        
        return res;
    }
};

 

以上是关于算法模板二叉树的主要内容,如果未能解决你的问题,请参考以下文章

风哥带你手撕算法之吃透二叉树(初版)

算法模板二叉树

二叉树算法模板

算法讲解二叉树 Ⅰ

风哥带你手撕算法之吃透二叉树

《寒假算法集训》(专题十五)二叉树