zoukankan      html  css  js  c++  java
  • 【LeetCode】树的遍历

    非递归中序遍历:

    思路:注释

        vector<int> inorderTraversal(TreeNode* root) {
            vector<int>ret;
            if(root == NULL) return ret;
            stack<TreeNode*>sta;
            TreeNode *p = root;
            while(!sta.empty() || p != NULL){
                // 当前节点不空 就一直左扎进
                while(p != NULL){
                    sta.push(p);
                    p = p -> left;
                }
                // 无左孩子 处理根节点 然后右孩子如果右空电话,p = NULL 下一次直接处理其父结点
                if(!sta.empty()){
                    p = sta.top();
                    sta.pop();
                    cout<<p->val<<endl;
                    ret.push_back(p->val);
                    p = p -> right;
                }
                
            }
            return ret;
        }

    非递归前序遍历:

    vector<int> preorderTraversal(TreeNode* root) {
            vector<int>ret;
            if(!root) return ret;
            stack<TreeNode *>s;
            TreeNode *p = root;
            while(p != NULL || !s.empty()){
                while(p){
                    cout<< p->val <<endl;
                    ret.push_back(p->val);
                    s.push(p);
                    p = p -> left;
                }
                if(!s.empty()){
                    p = s.top();
                    s.pop();
                    p = p -> right;
                }
            }
            return ret;
        }
  • 相关阅读:

    删与改

    基本操作
    名词解释
    Python内置函数(11)——complex
    Python内置函数(10)——float
    Python内置函数(9)——int
    Python内置函数(8)——bool
    Python内置函数(7)——sum
  • 原文地址:https://www.cnblogs.com/luntai/p/6894355.html
Copyright © 2011-2022 走看看