Skip to content

Update PseudoPalindromicPath.java #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 23 additions & 35 deletions src/PseudoPalindromicPath.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,45 +8,33 @@
* @author LBW
*/
public class PseudoPalindromicPath {
private int result = 0;
public int pseudoPalindromicPaths (TreeNode root) {
ArrayList<Integer> path = new ArrayList<>();
result = 0;
dfs(root, path);

return result;
}
private void dfs(TreeNode root, ArrayList<Integer> path) {
path.add(root.val);
if (root.left == null && root.right == null) { //到叶节点了,path已经构建完毕,可以判断是否为回文序列了。
if (isPseudoPalindrome(path))
result += 1;

static class MyList extends ArrayList<Integer> {
@Override
public boolean add(Integer integer) {
if (contains(integer)) {
remove(integer);
return true;
}
return super.add(integer);
}
if (root.left != null)
dfs(root.left, new ArrayList<>(path));
if (root.right != null)
dfs(root.right, new ArrayList<>(path));
}

public int pseudoPalindromicPaths(TreeNode root) {
return getCount(new MyList(), root);
}

private boolean isPseudoPalindrome(ArrayList<Integer> path) {
Hashtable<Integer, Integer> hashtable = new Hashtable<>();

for (Integer i: path) {
if (!hashtable.containsKey(i)) {
hashtable.put(i, 1);
}
else {
hashtable.put(i, hashtable.get(i)+1);
}
}
int oddCount = 0;
for (Map.Entry<Integer, Integer> entry: hashtable.entrySet()) {
if (entry.getValue() % 2 == 1)
oddCount += 1;
if (oddCount > 1)
return false;
private int getCount(MyList list, TreeNode root) {
if (root == null) return 0;

list.add(root.val);

if (root.left == null && root.right == null) {
return list.size() > 1 ? 0 : 1;
} else {
return getCount((MyList) list.clone(), root.left) +
getCount((MyList) list.clone(), root.right);
}
return true;
}

public static void main(String[] args) {
Expand Down