美文网首页
366. Find Leaves of Binary Tree

366. Find Leaves of Binary Tree

作者: Super_Alan | 来源:发表于2018-05-07 02:12 被阅读0次

    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<List<Integer>> findLeaves(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        dfsHeight(root, res);
        
        return res;
    }
    
    private int dfsHeight(TreeNode root, List<List<Integer>> 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<Integer> 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

          本文链接:https://www.haomeiwen.com/subject/yrnprftx.html