Code Interview Note
  • 0. Introduction
  • 1. Basic
    • Python Basic
    • Java Basic
    • Primitive Type
    • Basic Question
    • Number
  • 2. Array and Numbers
    • General
    • TwoSum
    • Buy and Sell Stock
    • SubArray
      • SubArray + HashMap
    • Sliding Window
      • Sliding Window At Most Problem
    • Word Break
    • Passes Problem
    • Majority Element
    • Partition Array
    • Sort Colors
    • Anagram
    • Ugly Number
    • TwoPointer
    • Swipe Line
    • Calculator
    • Sudoku
  • 2.1 String
    • String
    • Palindrome
    • Parentheses
    • Decode String
    • Calculator
    • Abbreviation
  • 3. Linkedlist
    • Dummy Node
    • Double Pointers
  • 4. Stack and Queue
    • General
    • Increase/Decrease Stack
  • 5. Binary Search
    • General
    • BS on result
    • Save the half which has result
    • Rotated Sorted Array
    • Split Array Largest Sum
  • 6. Binary Tree
    • General
    • Path Sum
    • Lowest Common Ancestor
    • BST
    • Convert
    • Traverse
    • Valid Ordered Tree
    • Construct Binary Tree
    • Tree depth and width
    • Vertical Order Traverse
  • 7. Heap
    • Geneal
    • TopK
  • 8. Simulation
    • General
    • Read4
    • Encode Decode
    • LRU/LFU
    • Robot
    • GetRandom O(1)
    • Probability
  • 9. DFS
    • Backtrack
    • General
    • Subset
    • Permutation
    • Combination
  • 10. HashTable
    • General
  • 11. Sort
    • General
  • 12. Recursion
    • General
  • 13. Dynamic Programming
    • Graph
    • General
    • Coordinate
    • Double Sequence
    • Longest Common Subsequence
    • Rolling Array
    • House Robber
    • Backpack
    • Memorization
    • Diagonal
  • 14. BFS
    • General
    • Number of Islands
    • The Maze
  • 15. Graph
    • Shortest Path
    • Undirected Graph
    • Topology Sort
    • Word Ladder
    • Tarjan's Algo
  • 16. Divide & Conquer
    • General
  • 17. UnionFind
    • General
    • Grouping
  • 18. Trie
    • General
    • Word Square
  • 19. Company Summary
    • Oracle
    • Amazon
      • DP
    • Google
    • Hackerrank
    • LinkedIn
  • 20. Design
  • 21. Math
  • Behavior Question
  • Internet
  • OS
Powered by GitBook
On this page
  • Avg depth of tree
  • 662. Maximum Width of Binary Tree

Was this helpful?

  1. 6. Binary Tree

Tree depth and width

Avg depth of tree

class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;
    public TreeNode(int val){
        this.val = val;
    }
}

double avgDepth(TreeNode root){
    if(root == null) return 0.0;
    Queue<TreeNode> q = new LinkedList<>();
    int sum = 0;
    int count = 0;
    int depth = 0;
    q.add(root);

    while(!q.isEmpty()){
        depth++;
        int size = q.size();
        for(int i=0; i<size; i++){
            TreeNode cur = q.poll();
            if(cur.left==null && cur.right==null){
                count++;
                sum += depth;
            }
            if(cur.left != null){
                q.add(cur.left);
            }
            if(cur.right != null){
                q.add(cur.right);
            }
        }
    }
    return (double)sum/count;
}

662. Maximum Width of Binary Tree

Iterative

  • 必須有個資料結構記住node index

  • Record the first node index

  • 找到level最後一個node的時候比較width

 def widthOfBinaryTree(self, root: TreeNode) -> int:
    res = 0
    left = 0
    q = []
    q.append((root, 1))
    
    while q:
        size = len(q)
        for i in range(size):
            node, idx = q.pop(0)
            if i == 0:
                left = idx
            if i == size-1:
                res = max(res, idx - left + 1)
            
            if node.left:
                q.append((node.left, idx*2))
            if node.right:
                q.append((node.right, idx*2+1))
    return res

dfs

  • 用一個list儲存每個level的第一個idx, 每個node都比較一次

int ans = 0;
public int widthOfBinaryTree(TreeNode root){ 
    List<Integer> list = new ArrayList<>();
    helper(root, 0, 0, list);
    return ans;
}

private void helper(TreeNode node, int level, int idx, List<Integer> list){
    if(node == null) return;

    // 放入這個level的第一個idx
    if(level == list.size()){
        list.add(idx);
    }

    ans = Math.max(ans, idx - list.get(level) + 1);
    helper(node.left, level+1, 2*idx, list);
    helper(node.right, level+1, 2*idx+1, list);
}
PreviousConstruct Binary TreeNextVertical Order Traverse

Last updated 4 years ago

Was this helpful?