微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

545. Boundary of Binary Tree

545. Boundary of Binary Tree

Still wrong result 

class Solution {
    public List<Integer> boundaryOfBinaryTree(TreeNode root) {
      List<Integer> result = new ArrayList<>();
      if(root == null){
        return result;
      }
      
      if(root.left == null || root.right == null) result.add(root.val);
      leftbound(root.left,result);
      leaves(root,result);
      rightbound(root,result);
      result.remove(result.size() - 1);
      return result;  
    }
    private void leftbound(TreeNode root,List<Integer> result){
      if(root == null || (root.left == null && root.right == null)){
        return;
      }
      result.add(root.val);
      if(root.left == null){
        leftbound(root.right,result);
      }else{
        leftbound(root.left,result);
      }
    }
    
    private void rightbound(TreeNode root,List<Integer> result){
      Deque<Integer> stack = new LinkedList<>();
      if(root == null || (root.left == null  && root.right == null)){
        return;
      }
      stack.push(root.val);
      if(root.right == null){
        rightbound(root.left,result);
      }else{
        rightbound(root.right,result);
      }
      int size = stack.size();
      for(int i = 0; i < size; i++){
          int cur = stack.pop();
          result.add(cur);
      }
    }
    
    private void leaves(TreeNode root,List<Integer> result){
      if(root == null) return;
      if(root.left == null && root.right == null) result.add(root.val);
      leaves(root.left,result);
      leaves(root.right,result);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐