题目
给你一棵二叉树,每个节点的值为 1 到 9 。我们称二叉树中的一条路径是 「伪回文」的,当它满足:路径经过的所有节点值的排列中,存在一个回文序列。
请你返回从根到叶子节点的所有路径中 伪回文 路径的数目。
解题思路
- 首先确定方法来判断是否为伪回文,可以通过Map来存储出现过的值,当第二次出现时删除,当Map大小小于等于1时则为伪回文;
- 通过递归遍历每一条从根节点到子节点的路径;
- 在进行左右子树遍历时需重新构建数据,避免数据干扰;
代码展示
class Solution {private int ans = 0;public int pseudoPalindromicPaths (TreeNode root) {Map<Integer,Integer> data = new HashMap<>();countPath(root, data);return ans;}public void countPath(TreeNode root, Map<Integer,Integer> data){if(root != null) {if (data.get(root.val) != null) {data.remove(root.val);} else {data.put(root.val, 0);}if (root.left == null && root.right == null) {if (data.size() == 1 || data.size() == 0) {ans++;}} else {if(root.left != null) {countPath(root.left, new HashMap<>(data));}if(root.right != null) {countPath(root.right, new HashMap<>(data));}}}}
}