Describe:
Given the root of a binary tree, flip the two fork tree
Solution:
Pre-sequence traversal binary tree, exchanging left and right child nodes
code example:
#include <iostream> #include <cstdio>using namespace std;class Node{ private: Node* left; Node* right; int value; public: int data () { return value; } node* left () { return left; } node* right () { return right; } node (Int _value): Value (_value) { left = Null; right = null; } void setleft ( Node* _left) { left = _left; } void setright (node* _right) { right = _right; }};class tree{ public: node* root;};/ /Create a binary tree node* construct () { node* n1 = new node (1); node* n2 = new node (2); node* n3 = new node (3); node* n4 = new node (4); node* n5 = new node (5); n1->setleft (n2); n1- >setright (n3); n3->setleft (N4); n3->setright (N5); &NBSP;&NBSP;&NBSP;RETURN&NBSP;N1;} Pre-order recursive traversal Void preorder (node* root) { if (null == root) { cout << endl; return; } cout << root->data () << " "; if ( Null != root->left ()) { preorder (Root->Left ()); } if (Null != root->right ()) { preorder (Root->right ()); }}//Flip Void image (Node* root) { if (null == root) { return; } if (Null == root->left () & & null == root->right ()) { return; } /* swap left and right subtree */ Node* temp = root->left (); root->setleft (Root->right ()); Root->setright (temp); &NBSP;&NBsp; if (Null != root->left ()) { image ( Root->left ()); } if (Null != root->right ()) { image (Root->right ()); }}int Main (void) { node* root = construct (); cout << endl; preorder (root); image (Root); cout << endl; preorder (Root); return 1;}
This article is from the "Precipice Program Ape" blog, please be sure to keep this source http://lth2015.blog.51cto.com/10613847/1683948
C + + implements two-tree mirroring (rollover)