Tree——No.872 Leaf-Similar Trees

Problem:

Consider all the leaves of a binary tree.  

From left to right order, the values of those leaves form a leaf value sequence.

Explanation:

判断两个二叉树是否叶子结点序列相同

My Thinking:

  1. 使用递归,将每个叶子结点存入list返回,再将list进行比较。
  2. 使用双端队列,利用层序遍历的思想,当某结点有孩子就将其加入队列前端,保证深度优先。

My Solution:

(1)

class Solution {
    public boolean leafSimilar(TreeNode root1, TreeNode root2) {
        List<Integer> result1=new ArrayList<>();
        List<Integer> result2=new ArrayList<>();
        return leaflist(root1,result1).equals(leaflist(root2,result2));
    }
    public List<Integer> leaflist(TreeNode root,List<Integer> result){
        if(root==null)
            return result;
        if(root.left==null && root.right==null){
            result.add(root.val);
            return result;
        }
        leaflist(root.left,result);
        return leaflist(root.right,result);
    }
}

(2)

class Solution {
    public boolean leafSimilar(TreeNode root1, TreeNode root2) {
        return leaflist(root1).equals(leaflist(root2));
    }
    public List<Integer> leaflist(TreeNode root){
        List<Integer> result=new ArrayList<>();
        Deque<TreeNode> queue=new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            int qsize=queue.size();
            for(int i=0;i<qsize;i++){
                TreeNode node=queue.poll();
                if(node.left==null && node.right==null){
                    result.add(node.val);
                }else{
                    if(node.right!=null){
                        queue.addFirst(node.right);
                    }
                    if(node.left!=null){
                        queue.addFirst(node.left);
                    }  
                    break;//一旦当前结点有孩子,就不能继续遍历原来队列的元素
                }
            }  
        }
        return result;
    }
}

Optimum Thinking:

在My Thinking上做了简化,直接改变传入的参数,而不返回list。

Optimum Solution:

class Solution {
    public boolean leafSimilar(TreeNode root1, TreeNode root2) {
        List<Integer> result1=new ArrayList<>();
        List<Integer> result2=new ArrayList<>();
        leaflist(root1,result1);
        leaflist(root2,result2);
        return result1.equals(result2);
    }
    public void leaflist(TreeNode root,List<Integer> result){
        if(root!=null){
            if(root.left==null && root.right==null){
                result.add(root.val);
        }
        leaflist(root.left,result);
        leaflist(root.right,result);
        }
        
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值