iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 28
0

題目:

https://leetcode.com/problems/invert-binary-tree/
反轉二元樹並回傳結果。

解題思路:

先交換節點,利用遞迴將某一邊之節點交換完成後,再換邊交換直到結束。

C版本:

struct TreeNode* invertTree(struct TreeNode* root) {
    if(root==NULL)
    {
        return NULL;
    }
    struct TreeNode *temp_root;
    temp_root = root->left;
    root->left = root->right;
    root->right = temp_root;
    invertTree(root->left);
    invertTree(root->right);
    return root;
}

Javascript版本:

var invertTree = function(root) {
    if(root == null)
        return null;
    var temp;
    temp = root.left;
    root.left = root.right;
    root.right = temp;
    invertTree(root.left);
    invertTree(root.right);
    return root;
};

程式Github分享:

https://github.com/SIAOYUCHEN/leetcode

相似主題分享:

https://ithelp.ithome.com.tw/users/20100009/ironman/2500
https://ithelp.ithome.com.tw/users/20113393/ironman/2169
https://ithelp.ithome.com.tw/users/20107480/ironman/2435
https://ithelp.ithome.com.tw/users/20107195/ironman/2382
https://ithelp.ithome.com.tw/users/20119871/ironman/2210
https://ithelp.ithome.com.tw/users/20106426/ironman/2136

本日分享:

Don't forget the past when you are successful, don't forget the future when you fail.
成功的時候不要忘記過去,失敗的時候不要忘記還有未來


上一篇
DAY27 Single Number
下一篇
DAY29 Find Peak Element
系列文
刷題記錄與人生分享34

尚未有邦友留言

立即登入留言