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