Invert a binary tree.
For example, convert
For example, convert
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void invert(TreeNode *root){ TreeNode *temp; temp = root->left; root->left = root->right; root->right = temp; if(root->left){ invert(root->left); } if(root->right){ invert(root->right); } } TreeNode* invertTree(TreeNode* root) { if(root == NULL){ return NULL; } invert(root); return root; } }; |
0 comments:
Post a Comment