Boundary of Binary Tree, Java clear code


  • 0
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        List<Integer> res = new ArrayList<>();
        Stack<Integer> rightBoundry = new Stack<>();
        public List<Integer> boundaryOfBinaryTree(TreeNode root) {
            if(root == null) return res;
            res.add(root.val);
            if(root.left == null && root.right == null){
                return res;
            }
            findleftBoundry(root.left);
            findleaves(root);
            findrightBoundry(root.right);
             while(rightBoundry.size() != 0){
                res.add(rightBoundry.pop());
            }
            return res;
        }
        public void findleftBoundry(TreeNode root){
            if(root == null) 
            return;
            if(root.left == null && root.right == null)
            return;
            res.add(root.val);
            if(root.left != null)
            findleftBoundry(root.left);
            else
            findleftBoundry(root.right);
        }
        public void findleaves(TreeNode root){
            if(root == null)return;
            if(root.left == null && root.right == null) res.add(root.val);
            findleaves(root.left);
            findleaves(root.right);
        }
        public void findrightBoundry(TreeNode root){
            if(root == null) return;
            if(root.left == null && root.right == null) return;
            rightBoundry.push(root.val);
            if(root.right != null)
            findrightBoundry(root.right);
            else
            findrightBoundry(root.left);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.