码迷,mamicode.com
首页 > 其他好文 > 详细

栈和递归的关系 144:Binary Tree Preorder Traversal

时间:2019-01-16 23:22:08      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:top   关系   rsa   alt   bubuko   span   技术分享   .com   while   

技术分享图片

前序遍历:根左右

//用栈来实现非递归解法
/*
* * 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; if(root == NULL) return res; stack<TreeNode*> stack; stack.push(root); while(!stack.empty()){ TreeNode* c = stack.top(); stack.pop(); res.push_back(c->val); if(c->right) stack.push(c->right); if(c->left) stack.push(c->left); } return res; } };
//递归解法,注意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> res; vector<int> preorderTraversal(TreeNode* root) { if(root){ res.push_back(root->val); preorderTraversal(root->left); preorderTraversal(root->right); } return 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> inorderTraversal(TreeNode* root) {
        stack<TreeNode*> st;
        vector<int> res;
        if(root == NULL) return res;  //若根节点为空则返回空
        TreeNode* p = root;
        while(p || !st.empty()){
            while(p){
                //先将根节点入栈,再将它所有的左节点入栈
                st.push(p);
                p = p->left;   
            }
            
            p = st.top();
            st.pop();
            res.push_back(p->val);
            p = p->right;
        }
        return res;
    }
};

 

栈和递归的关系 144:Binary Tree Preorder Traversal

标签:top   关系   rsa   alt   bubuko   span   技术分享   .com   while   

原文地址:https://www.cnblogs.com/Bella2017/p/10279952.html

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