leetcode 226 Invert Binary Tree 翻轉二叉樹
阿新 • • 發佈:2019-02-27
pub null bsp bin nod nbsp alt init pty
C++代碼,方法層序+互換左右孩子
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 //層序遍歷然後互換每一層的左右孩子 14 if(root==NULL) return root; 15 queue<TreeNode*> q; 16 q.push(root); 17 while(!q.empty()){ 18 TreeNode* cur=q.front(); 19 TreeNode* temp; 20 q.pop(); 21 if(cur->left!=NULL) q.push(cur->left);22 if(cur->right!=NULL) q.push(cur->right); 23 if(cur->left!=NULL&&cur->right==NULL){ 24 cur->right=cur->left;cur->left=NULL; 25 }else if(cur->left==NULL&&cur->right!=NULL){ 26 cur->left=cur->right;cur->right=NULL;27 }else if(cur->left!=NULL&&cur->right!=NULL){ 28 temp=cur->left; 29 cur->left=cur->right; 30 cur->right=temp; 31 } 32 } 33 return root; 34 } 35 };
leetcode 226 Invert Binary Tree 翻轉二叉樹