[閒聊] 每日LeetCode

作者: Rushia (みけねこ的鼻屎)   2022-09-14 23:02:29
1457. Pseudo-Palindromic Paths in a Binary Tree
題目:
給定一個Tree找出根節點到葉節點的所有Path中元素可以排列成迴文的Path數量。
思路:
使用回溯法來遞迴Tree,遞迴的過程統計數字0~9的出現次數,當遇到葉子節點時
判斷元素數量是否最多只有一個是奇數,若是則res+1。
Code:
class Solution {
int res = 0;
public int pseudoPalindromicPaths (TreeNode root) {
int[] count = new int[10];
DFS(root, count);
return res;
}
private void DFS(TreeNode root, int[] count) {
if(root == null) return;
count[root.val]++;
DFS(root.left, count);
if(root.left == null && root.right == null) {
int odd = 0;
for(int i = 1;i < 10 && odd < 2; i++)
if (count[i] % 2 != 0)
odd++;
if(odd < 2) res++;
}
DFS(root.right, count);
count[root.val]
作者: Poshintow (m_ _m)   2022-09-14 23:05:00
說人話 對不起

Links booklink

Contact Us: admin [ a t ] ucptt.com