545. Boundary of Binary Tree

解法一

思路

我觉得这是很经典的一道题,运用到了 DFS 和 stack 以及 list 的操作。
We can spearate the problem into three subproblems. Find left boundary, find leaves and find right boundary.
For left boundary, we always check the left child first and then right child if left child is null. If the child is not a leaf, add it into the result list.
For adding leaves, we use dfs to search all leaves from left to right and add them into list. The exit is when we find a leaf -> the node has no child.
For adding right boundary, it is similar to adding left boundary. The only difference is that we check its right child first and then left.

代码
class Solution{
    public List<Integer> boundaryOfBinaryTree(TreeNode root) {
        List<Integer> boundary = new ArrayList<>();
        if (root == null) {
          return boundary;
        }
        // No matter left subtree or/and right subtree is null, root is always the first one
        boundary.add(root.val);
        TreeNode t = root.left;
        while (t != null) {
            if (!isLeaf(t)) {
                boundary.add(t.val);
            }
            if (t.left != null) {
                t =t.left;
            } else if (t.right != null) {
                t = t.right;
            }
        }
        // Avoid adding root twice is toor itself is a leaf
        if (!isLeaf(root)) {
            addLeaves(boundary, root);
        }

        t = root.right;
        Stack<Integer> stack = new Stack<>();
        while (t != null) {
            if (!isLeaf(t)) {
                stack.push(t.val);
            }
            if (t.right != null) {
                t = t.right;
            } else if (t.left != null) {
                t = t.left;
            }
        }
        while (!stack.isEmpty()) {
            boundary.add(stack.pop());
        }
        return boundary;
    }

    private boolean isLeaf(TreeNode node) {
        return node.right == null && node.left == null;
    }

    private void addLeaves(List<Integer> boundary, TreeNode node) {
        if (isLeaf(node)) {
            boundary.add(node.val);
        } else {
            if (node.left != null) {
                addLeaves(boundary, node.left);
            }
            if (node.right != null) {
                addLeaves(boundary, node.right);
            }
        }
    }
}
复杂度分析

时间复杂度
Worst case O(n) because we traverse each of the node if all nodes are boundary.
空间复杂度
O(n) because we have a stack to store right boundary

解法二

思路
代码
复杂度分析

时间复杂度

  • 最好情况
  • 最坏情况
  • 平均情况
    空间复杂度

Takeaway

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!