[闲聊] 每日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