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 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

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