-
Notifications
You must be signed in to change notification settings - Fork 4
/
LeafSimilarTrees.java
82 lines (61 loc) · 1.77 KB
/
LeafSimilarTrees.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.
Note:
Both of the given trees will have between 1 and 100 nodes.
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean leafSimilar(TreeNode root1, TreeNode root2)
{
if (root1 == null || root2 == null)
{
if (root1 == null && root2 == null)
{
return true;
}
return false;
}
Stack<TreeNode> s1 = new Stack<>();
Stack<TreeNode> s2 = new Stack<>();
s1.push(root1);
s2.push(root2);
while (!s1.isEmpty() && !s2.isEmpty())
{
if (dfs(s1) != dfs(s2))
{
return false;
}
}
return (s1.isEmpty() && s2.isEmpty());
}
public int dfs(Stack<TreeNode> s)
{
while (true)
{
TreeNode curr = s.pop();
if (curr.right != null)
{
s.push(curr.right);
}
if (curr.left != null)
{
s.push(curr.left);
}
if (curr.left == null && curr.right == null)
{
return curr.val;
}
}
}
}