码迷,mamicode.com
首页 > 编程语言 > 详细

【算法模板】二叉树

时间:2017-05-08 20:59:13      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:stack   return   算法   values   class   end   order   bin   while   

模板:

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;
    }
};

 

【算法模板】二叉树

标签:stack   return   算法   values   class   end   order   bin   while   

原文地址:http://www.cnblogs.com/Atanisi/p/6827023.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!