Skip to content

1457. Pseudo-Palindromic Paths in a Binary Tree 👍

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int pseudoPalindromicPaths(TreeNode* root) {
    int ans = 0;
    dfs(root, 0, ans);
    return ans;
  }

 private:
  void dfs(TreeNode* root, int path, int& ans) {
    if (!root)
      return;
    if (!root->left && !root->right) {
      path ^= 1 << root->val;
      if ((path & (path - 1)) == 0)
        ++ans;
      return;
    }

    dfs(root->left, path ^ 1 << root->val, ans);
    dfs(root->right, path ^ 1 << root->val, ans);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int pseudoPalindromicPaths(TreeNode root) {
    dfs(root, 0);
    return ans;
  }

  private int ans = 0;

  private void dfs(TreeNode root, int path) {
    if (root == null)
      return;
    if (root.left == null && root.right == null) {
      path ^= 1 << root.val;
      if ((path & (path - 1)) == 0)
        ++ans;
      return;
    }

    dfs(root.left, path ^ 1 << root.val);
    dfs(root.right, path ^ 1 << root.val);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def pseudoPalindromicPaths(self, root: Optional[TreeNode]) -> int:
    ans = 0

    def dfs(root: Optional[TreeNode], path: int) -> None:
      nonlocal ans
      if not root:
        return
      if not root.left and not root.right:
        path ^= 1 << root.val
        if path & (path - 1) == 0:
          ans += 1
        return

      dfs(root.left, path ^ 1 << root.val)
      dfs(root.right, path ^ 1 << root.val)

    dfs(root, 0)
    return ans