The image of the Binary Tree "Sword refers to offer" and the Binary Tree "Sword refers to offer"
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Question link: http://www.nowcoder.com/practice/564f4c26aa584921bc75623e48ca3011? Rp = 1 & ru =/ta/coding-interviews & qru =/ta/coding-interviews/question-ranking
Description
Operate the given binary tree and convert it into an image of the source binary tree.
Input description:
Binary Tree image definition: Source Binary Tree
8
/\
6 10
/\/\
5 7 9 11
Image Binary Tree
8
/\
10 6
/\/\
11 9 7 5
Ideas
We first traverse each node of the tree in sequence. If the node to be traversed has a subnode, it will be switched to its subnode.
/*struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}};*/class Solution{public:void Mirror(TreeNode *root){if(root==nullptr)return ;if(root->left==nullptr && root->right==nullptr)return ;swap(root->left,root->right);if(root->left!=nullptr)Mirror(root->left);if(root->right!=nullptr)Mirror(root->right);}};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source