366. Find Leaves of Binary Tree

LeetCode Link

题目截图

depth and height are properties of a node:

The depth of a node is the number of edges from the node to the tree's root node.
A root node will have a depth of 0.

The height of a node is the number of edges on the longest path from the node to a leaf.
A leaf node will have a height of 0.


Properties of a tree:

The height of a tree would be the height of its root node,
or equivalently, the depth of its deepest node.

Note that depth doesn't make sense for a tree.

题解很巧妙的使用了 height. 与 Convert Sorted List to Binary Search Tree 有异曲同工之妙。

Find Leaves of Binary Tree 题解

public List> findLeaves(TreeNode root) {
    List> res = new ArrayList<>();
    dfsHeight(root, res);
    
    return res;
}

private int dfsHeight(TreeNode root, List> res) {
    if (root == null) {
        return -1;
    }
    
    int leftChildDepth = dfsHeight(root.left, res);
    int rightChildDepth = dfsHeight(root.right, res);
    int depth = Math.max(leftChildDepth, rightChildDepth) + 1;
    
    if (res.size() <= depth) {
        ArrayList list = new ArrayList<>();
        res.add(list);
    }
    
    res.get(depth).add(root.val);
    
    return depth;
}

Convert Sorted List to Binary Search Tree 题解

class Solution {
    ListNode currentListNode = null;
    
    public TreeNode sortedListToBST(ListNode head) {
        int size = getListLength(head);
        currentListNode = head;
        
        return inorderGenerator(size);
    }
    
    private TreeNode inorderGenerator(int len) {
        if (len == 0) {
            return null;
        }
        int half = len / 2;
        TreeNode leftChild = inorderGenerator(half);
        TreeNode root = new TreeNode(currentListNode.val);
        currentListNode = currentListNode.next;
        TreeNode rightChild = inorderGenerator(len - half -1); //这里的减1,是因为 root 已经占了一个 Node
        root.left = leftChild;
        root.right = rightChild;
        
        return root;
    }
    
    private int getListLength(ListNode head) {
        int size = 0;
        ListNode runner = head;
        while (runner != null) {
            size++;
            runner = runner.next;
        }
        return size;
    }
}

你可能感兴趣的:(366. Find Leaves of Binary Tree)