问题描述:
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.
思路: DFS,一个堆栈,两个arraylist,把叶节点全部找出来放在数组里比较
代码如下:
class Solution {
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
Stack<TreeNode> stack1=new Stack<>();
List<Integer> list1=new ArrayList<>();
List<Integer> list2=new ArrayList<>();
BFS(root1, stack1, list1);
BFS(root2, stack1, list2);
int[] arr1=new int[list1.size()];
for(int i=0; i<list1.size(); i++){
arr1[i]=list1.get(i);
}
int[] arr2=new int[list2.size()];
for(int i=0; i<list2.size();i++){
arr2[i]=list2.get(i);
}
return Arrays.equals(arr1, arr2);
}
private void BFS(TreeNode root, Stack<TreeNode> stack, List<Integer> list){
stack.push(root);
while(!stack.isEmpty()){
TreeNode currentNode=stack.pop();
if(currentNode.left!=null){
stack.push(currentNode.left);
}
if(currentNode.right!=null){
stack.push(currentNode.right);
}
if((currentNode.left==null)&&(currentNode.right==null)){
list.add(currentNode.val);
}
}
}
}
时间复杂度:O(m+n)