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

}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容