二叉树遍历
这两天抓紧把二叉树遍历复习了一遍,递归实现还是一如既往地简洁,迭代版本写了好久还是只实现了先序和中序,后续一直没搞明白,有空了再更新。
递归实现
void RecursionBackTree(TreeNode * root) {
if (root) {
//先续遍历
//cout << root->val << " ";
RecursionBackTree(root->left);
//中续遍历
//cout << root->val << " ";
RecursionBackTree(root->right);
//后续遍历
cout << root->val << " ";
}
}
迭代版本
先序遍历
//Preorder
void IterateFirstTraverse(TreeNode* root) {
if (!root) return;
stack<TreeNode*> st;
while (true) {
while (root) {
cout << root->val<<" ";
st.push(root->right);
root = root->left;
}
if (!st.empty()) {
root = st.top();
st.pop();
}
else {
break;
}
}
cout << endl;
}
中序遍历
void IterateTraverse(TreeNode* root) {
if (!root) return;
stack<TreeNode* > st;
//st.push(root);
//root = root->left;
while (true) {
while (root) { st.push(root); root = root->left; }
if (st.empty()) break;
root = st.top();
st.pop();
cout << root->val<<" ";
root = root->right;
}
cout << endl;
}