LeetCode 226 Invert Binary Tree
Problem: Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 Analysis: 1、helper function + recursion 一开始我用调用子函数,在子函数中递归的方式实现: 1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 private: 12 void swapNode (TreeNode* root) { 13 TreeNode *tmp = root->left; 14 root->left = root->right; 15 root->right = tmp; 16 17 if (root->left != NULL) { 18 swapNode (root->left); 19 } 20 21 if (root->right != NULL) { 22 swapNode