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); } }