leetcode Daily Challenge on December 29th, 2020.
Difficulty : Medium
Related Topics : DFS、Bit Manipulation、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.
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).
Input: root = [2,1,1,1,3,null,null,null,null,null,1] Output: 1 Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).
Input: root = [9] Output: 1
- The given binary tree will have between
1
and10^5
nodes.- Node values are digits from
1
to9
.
- mine
- Java
- DFS & HashSet
Runtime: 12 ms, faster than 70.36%, Memory Usage: 60.3 MB, less than 100.00% of Java online submissions
//O(N)time O(Depth)space public int res = 0; public int pseudoPalindromicPaths (TreeNode root) { HashSet<Integer> set = new HashSet<>(); dfs(root,set); return res; } public void dfs(TreeNode node, HashSet<Integer> set){ if(node == null){ return; } boolean in = set.contains(node.val); if(in){ set.remove(node.val); }else{ set.add(node.val); } if(node.left == null && node.right == null){ res += set.size() > 1 ? 0 : 1; }else{ dfs(node.left, set); dfs(node.right, set); } if(in){ set.add(node.val); }else{ set.remove(node.val); } }
- DFS & HashSet
- Java
- the most votes
- Bit Manipulation
Runtime: 2 ms, faster than 100.00%, Memory Usage: 57.2 MB, less than 100.00% of Java online submissions
//O(N)time O(1)space public int pseudoPalindromicPaths (TreeNode root) { return dfs(root, 0); } private int dfs(TreeNode root, int count) { if (root == null) return 0; count ^= 1 << (root.val - 1); int res = dfs(root.left, count) + dfs(root.right, count); if (root.left == root.right && (count & (count - 1)) == 0) res++; return res; }
- Bit Manipulation