欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Boundary of Binary Tree

程序员文章站 2022-04-02 18:49:44
...

题目
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<Integer> 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<Integer> list) {
        TreeNode curr = root;
        List<Integer> 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<Integer> 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<Integer> boundaryOfBinaryTree(TreeNode root) {
        List<Integer> 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;
    }

}