-
[LeetCode/easy] Symmentric-Tree (C++)알고리즘 문제풀이/LeetCode 2021. 2. 8. 01:47
leetcode.com/problems/symmetric-tree/
재귀를 이용하여 각각 루트노드에서 왼쪽 노드와 오른쪽 노드 값이 같은지 비교합니다.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool R(TreeNode* leftNode, TreeNode* rightNode) { if(leftNode == NULL && rightNode == NULL) return true; if(leftNode == NULL || rightNode == NULL) return false; if(leftNode -> val != rightNode -> val) return false; return R(leftNode -> left, rightNode -> right) && R(leftNode -> right, rightNode -> left); } bool isSymmetric(TreeNode* root) { if(root == NULL) return true; return R(root -> left, root -> right); } };
'알고리즘 문제풀이 > LeetCode' 카테고리의 다른 글
[LeetCode] Merge Two Sorted Lists (C++) (0) 2021.03.04 [LeetCode/easy] Single Number (C++) (0) 2021.02.08 [LeetCode/easy] Climbing-Stairs (C++) (0) 2021.02.08 [LeetCode/easy] Valid-Parentheses (C++) (0) 2021.02.07 [LeetCode/easy] Maximum Subarray (C++) (0) 2021.02.06