Preorder : 处理节点,移到左孩子,移到右孩子
void preorder(Node *root)
{
if (root == NULL) //<- Check if the currently passed node is empty
return; //<- if it is, return from the function back down the stack
cout << root->val << ", "; //<- if it wasn't empty, print its value
if (root->left != NULL) //<- check if the node to the left is empty
preorder(root->left); //<- if not recurse to the left child
if (root->right != NULL) //<- check if the node to the right is empty
preorder(root->right); //<- if not recurse to the right child
}
中序:向左移动,处理节点,向右移动
void inorder(Node *root)
{
if (root == NULL)
return;
if (root->left != NULL) //<- check if the node to the left is empty
inorder(root->left); //<- if not recurse to the left child
cout << root->val << ", ";
if (root->right != NULL) //<- check if the node to the right is empty
inorder(root->right); //<- if not recurse to the right child
}
Postorder : 移动到左边节点,移动到右边节点,处理节点
void postorder(Node *root)
{
if (root == NULL)
return;
if (root->left != NULL) //<- check if the node to the left is empty
postorder(root->left); //<- if not recurse to the left child
if (root->right != NULL) //<- check if the node to the right is empty
postorder(root->right); //<- if not recurse to the right child
cout << root->val << ", "
}