226. Invert Binary Tree
My SubmissionsTotal Accepted: 57653 Total Submissions: 136144 Difficulty: EasyInvert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1Trivia:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
Subscribe to see which companies asked this question
Hide Tags Tree/** * 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: //將根節點反轉,並獲取翻轉後該根節點的指針 TreeNode* invertTree(TreeNode* root) { if(root == NULL){ return NULL; }else{ //這樣做將:樹的底層先被真正交換,然後其上一層才做反轉 TreeNode* newleft = invertTree(root->right); TreeNode* newright = invertTree(root->left); root->left = newleft; root->right = newright; return root; } } };