본문 바로가기

재귀16

[leetcode 226] Invert Binary Tree Invert a binary tree. Example: Input: Output: 문제 풀이: - 재귀...난이도는 쉬움인데 해도 해도 모르겠다 재귀는 - 현재 노드에서 왼쪽 서브트리와 오른쪽 서브트리를 바꾸는 것이 중점 - 왼쪽 서브트리와 오른쪽 서브트리를 새로 만들어서 붙인다. class Solution { public: TreeNode* invertTree(TreeNode* root) { if(root == nullptr){ return root; } TreeNode* right = invertTree(root->right); TreeNode* left = invertTree(root->left); root->left = right; root->right = left; return root; } }; 2020. 10. 30.
[leetcode 104] Maximum Depth of Binary Tree Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. Example: Given binary tree [3,9,20,null,null,15,7], return 3 문제 풀이: -난이도 easy recursion 사용 현재 노드가 nullptr이면 0을 리턴 그렇지 않으면 1씩 더해서 리턴한다. 이 때 왼쪽과 오른쪽 중 큰 값에 1을 더해서 리턴한다. class Solution { public: int m.. 2020. 10. 23.
[leetcode 337] House Robber III The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night. Determine t.. 2020. 10. 20.
[leetcode 437] Path Sum III You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes). The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000. Example: root = [10,5,-3,3,2,null,11,3,.. 2020. 10. 18.