二叉树遍历

1.首先是二叉树的 结构体

  struct TreeNode{

      TreeNode *right;

    TreeNode *left;

   int val;

   TreeNode(int x): val(x),right(NULL),left(NULL);{}

}

接着是二叉树前序中序后序遍历;

1.前序遍历

方法1:

  stack<TreeNode*> st{{root}};

  vector<int> res;

while(!st.epmty()){

TreeNode* tmp=st.top();st.pop();

res.push_back(tmp->val);

if(tmp->right) st.push(tmp->right);

if(tmp->left) st.push(tmp->left);

} return res;

方法2:利用栈和辅助节点;

stack<TreeNode*> st;

TreeNode *p=root;

vector<int> res;

while(!st.empty()||p){

if(p){  st,push(p); 

      res.push(p->val);

        p=p->left;}

else {  p=st.top();st.pop();

           p=p->right;

}}  return res;

中序遍历:左根右 
 
同样方法1;辅助节点和堆栈
vector<int> res;
        stack<TreeNode*> s;
        TreeNode *p = root;
        while (p || !s.empty()) {
            while (p) {
                s.push(p);
                p = p->left;
            }//一直压入左节点
            p = s.top(); s.pop();
            res.push_back(p->val);//先将最左子节点输出 
            p = p->right;
        }
        return res;
    }
};
方法2:和前序遍历方法一样 只不过是输出的顺序发生了变化
vector<int> res;
        stack<TreeNode*> s;
        TreeNode *p = root;
        while (!s.empty() || p) {
            if (p) {
                s.push(p);
//  前序遍历是在此处将节点值加入向量中。
                p = p->left;
            } else {
                p = s.top(); s.pop();
                res.push_back(p->val);//注意在此处将节点值加入向量中
                p = p->right;
            }
        }
        return res;
后序遍历:左右根
if (!root) return {};//第一种方法明天再看;
        vector<int> res;
        stack<TreeNode*> s{{root}};
        TreeNode *head = root;//辅助节点
        while (!s.empty()) {
            TreeNode *t = s.top();
            if ((!t->left && !t->right) || t->left == head || t->right == head) {
                res.push_back(t->val);
                s.pop();
                head = t;
            } else {
                if (t->right) s.push(t->right);
                if (t->left) s.push(t->left);
            }
        }
        return res;
//利用辅助节点 先判定当前结点有没有左右子节点 或者他的左子节点或者右子节点
是不是
 
方法2: 先序遍历是根左右  后序遍历是左右根 我们改动先序遍历成 
根右左 然后把res reverse 一下就可以啦;
stack<ListNode*> st{{root}};    
while(!st.empty()||p) 
        {if(p){  st.push(p);
        res.push_back(p->val);
        p=p->right;
}      else 
     {    p=st.top();st.pop();
          p=p->left;
}     reverse(res.begin(),res.end());
   return res;
 
层次遍历: 用一个queue即可 ,此处不写了。
 

 

posted @ 2020-10-10 15:46  sjtu小帅哥  阅读(101)  评论(0)    收藏  举报