翻转一棵二叉树。
4 / 2 7 / \ / 1 3 6 9
转换为:
4 / 7 2 / \ / 9 6 3 1 注意点:小心不要把程序写成下面这样: 1 root->left = invertTree(root->right); 2 root->right = invert(root->left); 因为第一行的root->left指向的内容已近改变,要用一个变量来保存原来的root->left的值
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 public: 12 TreeNode* invertTree(TreeNode* root) { 13 if(root == NULL) return NULL; 14 TreeNode* temp = root->left; 15 root->left = invertTree(root->right); 16 root->right = invertTree(temp); 17 return root; 18 } 19 };
原文地址:https://www.cnblogs.com/mr-stn/p/8978015.html
时间: 2024-10-07 15:50:17