/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ voidtraversal(TreeNode* root){ stack<TreeNode*> s; TreeNode* current = root;
while (!s.empty() || current) { if (current) { s.push(current); //(1) current = current->left; } else { current = s.top()->right; // (3) s.pop(); // if we pop the node, then we do not have (5) } } }
voidinorderTraversal(TreeNode* root){ TreeNode* current = root; while (current != NULL) { if (current->left == NULL) { cout << current->val; current = current->right; } else { TreeNode* prev = current->left; while (prev->right != NULL && prev->right != current) { prev = prev->right; }
if (prev->right == NULL) { prev->right = current; current = current->left; } elseif (prev->right == current) { cout << current->val; current = current->right; prev->right = NULL; } } } }
基本思路是:
1 2 3 4 5 6 7 8 9
1. Initialize current as root 2. While current is not NULL If current does not have left child a) Print current’s data b) Go to the right, i.e., current = current->right Else a) Make current as right child of the rightmost node in current's left subtree b) Go to this left child, i.e., current = current->left