https://leetcode.com/problems/same-tree/
| 6 | * https://leetcode.com/problems/same-tree/ |
| 7 | */ |
| 8 | public class Sanghoo { |
| 9 | |
| 10 | public boolean isSameTree(TreeNode p, TreeNode q) { |
| 11 | // 모두 null이면 true |
| 12 | if(p == null && q == null) return true; |
| 13 | // 위에서 모두 null이 아님을 확인했으니, 하나라도 null이면 false |
| 14 | if(p == null || q == null) return false; |
| 15 | |
| 16 | Stack<TreeNode> stack = new Stack<>(); |
| 17 | |
| 18 | stack.push(p); |
| 19 | stack.push(q); |
| 20 | |
| 21 | while(!stack.isEmpty()) { |
| 22 | TreeNode p1 = stack.pop(); |
| 23 | TreeNode p2 = stack.pop(); |
| 24 | |
| 25 | // 값이 다르면 당연히 false |
| 26 | if(p1.val != p2.val) return false; |
| 27 | |
| 28 | // 좌측 자식노드가 존재하면 넣음 |
| 29 | // 이때 두 트리 모두 존재햐아하므로 삽입 후 스택의 크기로 검증(두 트리 모두 자식이 있는지) |
| 30 | if(p1.left != null) stack.push(p1.left); |
| 31 | if(p2.left != null) stack.push(p2.left); |
| 32 | if(stack.size() % 2 != 0) return false; |
| 33 | |
| 34 | // 우측도 위와 동일 |
| 35 | if(p1.righ != null) stack.push(p1.right); |
| 36 | if(p2.right != null) stack.push(p2.right); |
| 37 | if(stack.size() % 2 != 0) return false; |
| 38 | } |
| 39 | |
| 40 | return true; |
| 41 | } |
| 42 | |
| 43 | } |
nothing calls this directly
no outgoing calls
no test coverage detected