본문 바로가기

Algorithm/Leet Code

LeetCode #617 MergeTwoBinaryTrees. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접,연결..

LeetCode #617 MergeTwoBinaryTrees. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접,연결리스트

 

Pointer hell..

포인터 지옥..

 

 

Runtime: 40 ms, faster than 86.90% of C++ online submissions for Merge Two Binary Trees.

 

Memory Usage: 24 MB, less than 6.42% of C++ online submissions for Merge Two Binary Trees.

 

 

LeetCode #617

Q.

 Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

 

 이진트리가 두개 주어지고, 하나를 다른 한개에 덮어쓴다하면 어떤 노드는 중복되고, 어떤 것은 중복되지 않는다.

두개의 바이너리 트리를 병합해서 새로 한개를 만들어야한다. 병합 규칙은, 만일 노드가 겹치면 노드의 합을 새로운 병합 노드로 만든다. 반면에, 그냥 널이 아닌 노드는 그대로 새 트리에 쓰여진다.

 

 

Example 1:

 

Note: The merging process must start from the root nodes of both trees.

 

 

 

Process

// Process
//1. Input two tree rootNode
//2. Prepare return rootNode
//3. *12, Call recursive mergeSum
//4. Return resultRootNode

//recursiveMergeSum()
//1. Input two treeNode
//2. Check if one of them is not null at least
// 2.1. If so -> add or put them to resultTreeNode
//3. Move to next level node (left)
//4. Move to next level node (right)
//5. Finish

 

 

// 처리과정

//1. 두개의 바이너리트리 루트노드를 입력받는다.

//2. 리턴할 루트노드를 만든다.

//3. *12 순서로 재귀 함수 호출한다.

//4. 결과 반환한다.

 

//리커시브병합

//1. 리턴노드와 두개의 트리노드 입력받는다.

//2. 트리노드 입력받은 것이 널인지 확인해서

// 2.1. 조건에 맞게 리턴노드 채워넣어준다.

// 2.2. 조건에 맞게 재귀 호출한다.

//3. 끝낸다.

 

Code.. lemme see example code!!!

코드.. 예제코드를 보자!!!

 

 

 

class Solution {
public:
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        TreeNode* resultRootNode;
        
        recursiveMergeSum(&resultRootNode, t1, t2);
        
        return resultRootNode;
    }
private:
    void recursiveMergeSum(TreeNode** resultTree, TreeNode* node1, TreeNode* node2) {
        if (node1 != 0 && node2 != 0) {
            *resultTree = new TreeNode(node1->val + node2->val);
            recursiveMergeSum(&((*resultTree)->left), node1->left, node2->left);
            recursiveMergeSum(&((*resultTree)->right), node1->right, node2->right);
        } else if (node1 != 0 && node2 == 0) {
            *resultTree = new TreeNode(node1->val);
            recursiveMergeSum(&((*resultTree)->left), node1->left, 0);
            recursiveMergeSum(&((*resultTree)->right), node1->right, 0);
        } else if (node1 == 0 && node2 != 0) {
            *resultTree = new TreeNode(node2->val);
            recursiveMergeSum(&((*resultTree)->left), 0, node2->left);
            recursiveMergeSum(&((*resultTree)->right), 0, node2->right);
        } else { // both are NULL
            *resultTree = 0;
        }
    }
};

 

 

 

Something else you might like...?

 

 

2019/05/26 - [Algorithm/Leet Code] - LeetCode #965 UnivaluedBinaryTree. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접,연결..

2019/05/20 - [Algorithm/Leet Code] - LeetCode #509 FibonacciNumber. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접,연결리스..

2019/05/19 - [Algorithm/Leet Code] - LeetCode #506 RelativeRanks. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접,연결리스트

2019/05/13 - [Algorithm/Leet Code] - LeetCode #383 RansomNote. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접,연결리스트

2019/04/28 - [Algorithm/Leet Code] - LeetCode #121 BestTimeToBuyAndSellStock. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접

2019/04/24 - [Algorithm/Leet Code] - LeetCode #119 Pascal'sTriangle2. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접, 파스칼..

2019/04/24 - [Algorithm/Leet Code] - LeetCode #104 MaximumDepthOfBinaryTree. Algorithm,알고리즘,LeetCode,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive,datastructure,techinterview,coding,코딩인터뷰,기술면접

 

 

2019/04/14 - [Programming/C++] - C++ Math - sqrt (square root, 제곱근, 루트). stl, math.h, 씨쁠쁠, example code, 예제코드

 

 

2018/10/19 - [Programming/Design Pattern ] - Design pattern - Prototype (디자인패턴 - 프로토타입) / Java C++ C#

 

 

2019/01/12 - [Algorithm/Code Fights (Code Signal)] - Aracade Intro #60 sudoku. Algorithm,알고리즘,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive

2019/01/12 - [Algorithm/Code Fights (Code Signal)] - Aracade Intro #59 spiralNumbers. Algorithm,알고리즘,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive

2019/01/08 - [Algorithm/Code Fights (Code Signal)] - Aracade Intro #58 messageFromBinaryCode. Algorithm,알고리즘,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive

2019/01/07 - [Algorithm/Code Fights (Code Signal)] - Aracade Intro #57 fileNaming. Algorithm,알고리즘,Codefights,CodeSignal,코드파이트,코드시그널,예제,문제해결능력,example,c++,java,재귀,recursive

2019/01/04 - [Algorithm/Code Fights (Code Signal)] - Aracade Intro #56 digitsProduct. Algorithm, 알고리즘, Codefights, CodeSignal, 코드파이트, 코드시그널, 예제,문제해결능력,example, c++ java c# scalar

2019/01/04 - [Algorithm/Code Fights (Code Signal)] - Aracade Intro #55 differentSquares. Algorithm, 알고리즘, Codefights, CodeSignal, 코드파이트, 코드시그널, 예제,문제해결능력,example, c++ java c# scalar

 

 

2018/12/28 - [Programming/Software Architecture] - Perfecting OO's Small Classes and Short Methods. 완벽한 객체지향의 작은 클래스와 짧은 메소드, Book:ThoughtWorks Anthology, Java,cpp,자바,oop,좋은코드,객체지향프로그래밍 - (#9, Tell, Don't Ask)

2018/12/26 - [Programming/Software Architecture] - Perfecting OO's Small Classes and Short Methods. 완벽한 객체지향의 작은 클래스와 짧은 메소드, Book:ThoughtWorks Anthology, Java,cpp,자바,oop,좋은코드,객체지향프로그래밍 (1)

 

 

2019/01/14 - [Programming/Java] - 자바 메모리 누수 체크/확인/고치는 방법, Memory leak check/fix in Java application, cleanCode/좋은코드/oop/객체지향

 

 

2019/02/19 - [Life/Health care] - Lysine 라이신 usage/side effects/dosage 효과/효능/부작용/성인,소아 용법, 복용법

2019/02/16 - [Life/Health care] - Finasteride 피나스테라이드,탈모약 usage/side effects/dosage 효능/부작용/효과/sexual effect/두타스테라이드/프로페시아/propecia/finpecia/카피약/copy drug/hair loss

2019/02/25 - [Life/Health care] - Folic Acid 엽산 vitaminB9,비타민M usage/side effects/dosage 효과/효능/부작용/성인,소아 용법, 복용법

2019/02/28 - [Life/Health care] - Vitamin K, 비타민 K usage/side effects/dosage 효능/부작용/성인,소아 용법

2019/03/03 - [Life/Health care] - Vitamin B1, Thiamine, 비타민 B1, 티아민 usage/side effects/dosage 효능/부작용/성인,소아 용법