标签:als style 左右 queue win int str temp tree
左右翻转一棵树,两种方法
第一种是非递归方法,借助层次遍历来实现,交换每一个节点的左右子节点即可
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) 14 return NULL; 15 queue<TreeNode*> que; 16 que.push(root); 17 while(!que.empty()) 18 { 19 TreeNode* p=que.front(); 20 que.pop(); 21 TreeNode* temp=p->left; 22 p->left=p->right; 23 p->right=temp; 24 if(p->left!=NULL) 25 que.push(p->left); 26 if(p->right!=NULL) 27 que.push(p->right); 28 } 29 return root; 30 } 31 };
第二种方法是递归,递归交换所有节点的左右子节点
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 static int wing=[]() 11 { 12 std::ios::sync_with_stdio(false); 13 cin.tie(NULL); 14 return 0; 15 }(); 16 17 class Solution 18 { 19 public: 20 TreeNode* invertTree(TreeNode* root) 21 { 22 change(root); 23 return root; 24 } 25 26 void change(TreeNode * root) 27 { 28 if(root==NULL) 29 return; 30 TreeNode *temp=root->right; 31 root->right=root->left; 32 root->left=temp; 33 change(root->left); 34 change(root->right); 35 } 36 37 38 };
标签:als style 左右 queue win int str temp tree
原文地址:https://www.cnblogs.com/zhuangbijingdeboke/p/9078641.html