2022-9-11

23 阅读1分钟

算法

使用bfs遍历,增加一个depth记录层数

var maxDepth = function(root) { 
  if(!root) { return 0; } 
  const arr =[root]; 
  let depth = 0; 
  while(arr.length) { 
      let len = arr.length; 
      while(len) { 
          const curNode = arr.shift(); 
          curNode.left && arr.push(curNode.left); 
          curNode.right && arr.push(curNode.right); len--; 
      } depth++;
  } 
  return depth; 
};

ts

// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'

type cases = [
  Expect<Equal<If<true, 'a', 'b'>, 'a'>>,
  Expect<Equal<If<false, 'a', 2>, 2>>,
]

// @ts-expect-error
type error = If<null, 'a', 'b'>


// ============= Your Code Here =============
// 就是一个三目判断,返回对应的值
type If<C, T, F> = C extends true ? T: C extends false ? F : error;