程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> (LeetCode OJ) Invert Binary Tree【226】

(LeetCode OJ) Invert Binary Tree【226】

編輯:關於C++

226. Invert Binary Tree

My SubmissionsTotal Accepted: 57653 Total Submissions: 136144 Difficulty: Easy

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9
to
     4
   /   \
  7     2
 / \   / \
9   6 3   1
Trivia:
This problem was inspired by this original tweet by Max Howell:
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;
        }
    } 
};
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved