Trees Flashcards

1
Q

Right side view of Tree using DFS

A

Use hashmap at each level. As you traverse, right HashMap will contain Right Elements

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Canonical Traversal

A
public boolean flipEquiv(TreeNode root1, TreeNode root2) {
        List vals1 = new ArrayList();
        List vals2 = new ArrayList();
        dfs(root1, vals1);
        dfs(root2, vals2);
        return vals1.equals(vals2);
    }
public void dfs(TreeNode node, List vals) {
    if (node != null) {
        vals.add(node.val);
        int L = node.left != null ? node.left.val : -1;
        int R = node.right != null ? node.right.val : -1;
            if (L < R) {
                dfs(node.left, vals);
                dfs(node.right, vals);
            } else {
                dfs(node.right, vals);
                dfs(node.left, vals);
            }
        vals.add(null);
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

To display elements level wise using DFS

A

List> result;

Inside DFS

if(result.size()== depth)
{
      res.add(new ArrayList());
}
res.get(depth).add(root.val);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly