Topic:
Given the source binary tree, the design algorithm realizes its mirror image.
Ideas:
For the problem of binary tree, it is necessary to consider the non recursive implementation of the recursive method.
This is a good recursive implementation, for the first node traversal, each exchange its left and right subtree. Then recursively calls to its subtree.
For non-recursive implementations, you need to use a secondary stack to hold the header nodes. (Sequence traversal)
Note:
The binary tree node is defined as follows:
typedef int DATATYPE;
struct Node
{
DataType Val;
struct Node *left;
struct Node *right;
Node (DataType _val):
Val (_val), left (null), right (null) {}
};
Paste Code:
void Mirror (TreeNode *proot) {if (0) {//recursive implementation if (Proot = = NULL) {
Return
} TreeNode *temp;
temp = proot->left;
Proot->left = proot->right;
Proot->right = temp;
Mirror (Proot->left);
Mirror (Proot->right);
else {//non-recursive implementation (requires the use of a secondary stack) stack<treenode*> Stk;
if (Proot = = NULL) {return;
} stk.push (Proot); If the stack is not empty the description also needs to traverse the while (!stk.empty ()) {//Get the current traversal subtree header node TreeNode *
Head = Stk.top ();
Stk.pop ();
Any subtree of the head node is not empty and needs to be exchanged if (Head->left | | head->right) {TreeNode *temp;
temp = head->left; Head->left = head->right;
Head->right = temp; //Press into the new head node if (head->left) {Stk.push (head->
; left);
} if (head->right) {Stk.push (head->right);
}} return; }