LZ大大,二叉排序树没有要求必须最低深度吧 我这么写的: function TreeNode(val) { this.val = val this.left = null this.right = null } function createTree(arr) { if (!arr.length) return null const root = new TreeNode(arr[0]) if (arr.length === 1) return root const left = arr.filter(item => item < arr[0]), right = arr.filter(item => item > arr[0]) root.left = createTree(left) root.right = createTree(right) return root } function inorder(root) { if (!root) return [] const res = [] const helper = root => { if (!root) return helper(root.left) res.push(root.val) helper(root.right) } helper(root) return res } console.log(inorder(createTree([4, 2, 5, 1, 3, 6, 7, 9]))) //[1, 2, 3, 4, 5, 6, 7, 9]
1 2

相关推荐

牛客网
牛客企业服务