力扣精选top面试题-------- 二叉树的遍历

在这里插入图片描述
题目链接

思路:
这道题其实是模板题,必须好好掌握二叉树的遍历方式,我这边了解到的共有三种:递归,非递归,Morries算法,这些知识后面我会总结起来,现在这里就用递归算法来解决。

代码:

/**
 * 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> q;
    void func(TreeNode* root){
        if(root==NULL)  return ;
        func(root->left);
        q.push_back(root->val);
        func(root->right);
    }
    vector<int> inorderTraversal(TreeNode* root) {
        func(root);
        return q;
    }
};


//非递归版本  中序和先序的代码是一样的,只不过打印节点的值位置不一样而已,后序比较麻烦
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> q;
        stack<TreeNode*> st;
        while( !(st.size()==0 && root==NULL) ){
            if(root!=NULL){
                st.push(root);
                root = root->left;
            }else{
                auto it = st.top();
                st.pop();
                q.push_back(it->val);
                root = it->right;
            }
        }
        return q;
    }
};

//非递归后序遍历
//明确只有两种情况:一是没有右节点,二是prev(上一次访问打印的点)是该节点的右节点
class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> res;
        if (root == nullptr) {
            return res;
        }

        stack<TreeNode *> stk;
        TreeNode *prev = nullptr;
        while (root != nullptr || !stk.empty()) {
            if(root!=NULL){
                stk.push(root);
                root=root->left;
            }else{
                root = stk.top();

                if(root->right==nullptr || root->right==prev){
                    res.push_back(root->val);
                    stk.pop();
                    prev = root;
                    root = nullptr;
                }else{
                    root=root->right;
                }
            }
        }
        return res;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值