Pseudo-Palindromic Paths in a Binary Tree

Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.

Return the number of pseudo-palindromic paths going from the root node to leaf nodes.

Example 1:

Input: root = [2,3,1,3,1,null,1]
Output: 2 
Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).

思路:就是收集每條root 到leaf的數字,然後判斷是否能形成palindorme。注意,收集的最後一步,也要用backtracking,把leaf delete掉;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int pseudoPalindromicPaths (TreeNode root) {
        List<List<Integer>> lists = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        dfs(root, lists, list);
        int count = 0;
        for(List<Integer> l : lists) {
            if(isvalid(l)) {
                count++;
            }
        }
        return count;
    }
    
    private void dfs(TreeNode root, List<List<Integer>> lists, List<Integer> list) {
        if(root == null) {
            return;
        }
        if(root.left == null && root.right == null) {
            list.add(root.val);
            lists.add(new ArrayList<Integer>(list));
            list.remove(list.size() - 1);
            return;
        }
        list.add(root.val);
        dfs(root.left, lists, list);
        list.remove(list.size() - 1);
        
        list.add(root.val);
        dfs(root.right, lists, list);
        list.remove(list.size() - 1);
    }
    
    private boolean isvalid(List<Integer> list) {
        HashMap<Integer, Integer> countmap = new HashMap<>();
        int oddcount = 0;
        for(Integer i: list) {
            countmap.put(i, countmap.getOrDefault(i, 0) + 1);
        }
        
        for(Integer key: countmap.keySet()) {
            if(countmap.get(key) % 2 == 1) {
                oddcount++;
            }
        }
        return oddcount <= 1;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章