Boundary of Binary Tree

题目
Given a binary tree, return the values of its boundary in anti-clockwise direction starting from root. Boundary includes left boundary, leaves, and right boundary in order without duplicate nodes.

Left boundary is defined as the path from root to the left-most node. Right boundary is defined as the path from root to the right-most node. If the root doesn't have left subtree or right subtree, then the root itself is left boundary or right boundary. Note this definition only applies to the input binary tree, and not applies to any subtrees.

The left-most node is defined as a leaf node you could reach when you always firstly travel to the left subtree if exists. If not, travel to the right subtree. Repeat until you reach a leaf node.

The right-most node is also defined by the same way with left and right exchanged.

答案

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public void lboundary(TreeNode root, List list) {
        TreeNode curr = root;
        while(curr != null) {
            // Do not add the left-most node, will add this node in leaves()
            if(curr.left == null && curr.right == null) break;

            list.add(curr.val);
            curr = (curr.left != null)? curr.left : ((curr.right != null) ? curr.right:null);
        }
    }

    public void rboundary(TreeNode root, List list) {
        TreeNode curr = root;
        List rlist = new ArrayList<>();
        while(curr != null) {
            // Do not add the right-most node, will add this node in leaves()
            if(curr.left == null && curr.right == null) break;

            rlist.add(0, curr.val);
            curr = (curr.right != null)? curr.right : ((curr.left != null) ? curr.left:null);

        }
        list.addAll(rlist);
    }

    public void leaves(TreeNode root, List list) {
        if(root == null) return;
        if(root.left == null && root.right == null) {
            list.add(root.val);
            return;
        }
        leaves(root.left, list);
        leaves(root.right, list);
    }


    public List boundaryOfBinaryTree(TreeNode root) {
        List list = new ArrayList<>();
        if(root == null) return list;

        list.add(root.val);
        lboundary(root.left, list);
        // We don't want root to be recognized as leaves
        leaves(root.left, list);
        leaves(root.right, list);
        rboundary(root.right, list);

        return list;
    }

}

你可能感兴趣的:(Boundary of Binary Tree)