二叉树前序遍历
C++二叉树前序遍历基本思想
申请一个新的栈为stk,将头节点压入栈中
每次从stk中弹出栈顶节点,记为cur,然后打印cur的值
当cur的右孩子不为空,压入栈中
当cur的左孩子不为空,压入栈中
不断重复,直到stk为空
C++二叉树前序遍历代码
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int val,TreeNode *left,TreeNode *right):val(val),left(left),right(right){};
}
//递归写法
void postSortCure(TreeNode *root)
{
if(root == NULL) return;
cout<<root->val<<" ";
postSortCure(root->left);
postSortCure(root->right);
}
//非递归写法
void postSort(TreeNode* root)
{
stack<TreeNode*> stk;
stk.push(root);
while(!stk.empty())
{
TreeNode* cur = stk.top();
stk.pop();
cout<<cur->val<<" ";
if(cur->right) stk.push(cur->right);
if(cur->left) stk.push(cur->left);
}
}