- LeetCode
- 1. 完全二叉树的节点个数
- 2. 先序、中序、后序遍历
- 105. 从前序与中序遍历序列构造二叉树">105. 从前序与中序遍历序列构造二叉树
- 106. 从中序与后序遍历序列构造二叉树">106. 从中序与后序遍历序列构造二叉树
- 110. 平衡二叉树">110. 平衡二叉树
- 5. 层序遍历
- 6. 叶子统计
- 7. 最大二叉树 I
- 998. 最大二叉树 II">998. 最大二叉树 II
- 589. N叉树的前序遍历">589. N叉树的前序遍历
- 111. 二叉树的最小深度">111. 二叉树的最小深度
- 104. 二叉树的最大深度(递归和bfs)">104. 二叉树的最大深度(递归和bfs)
- 124. 二叉树中的最大路径和">124. 二叉树中的最大路径和
- 剑指Offer
这里只收集了中等题
LeetCode
1. 完全二叉树的节点个数
完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
// 递归 O(logn)func countNodes(root *TreeNode) int {if root == nil {return 0}return 1 + countNodes(root.Left) + countNodes(root.Right)}
2. 先序、中序、后序遍历
这里只写了中序代码
中序 递归:
//时间复杂度:O(n),其中 n 为二叉树节点的个数。二叉树的遍历中每个节点会被访问一次且只会被访问一次。//空间复杂度:O(n)。空间复杂度取决于递归的栈深度,而栈深度在二叉树为一条链的情况下会达到 O(n) 的级别func inorderTraversal(root *TreeNode) (res []int) {var inorder func (node *TreeNode)inorder = func (node *TreeNode) {if node == nil {return}inorder(node.Left)res = append(res, node.Val)inorder(node.Right)}inorder(root)return}
中序 栈模拟:
func threeOrders( t *TreeNode ) [][]int {s := []*TreeNode{}ret := make([][]int, 3)// 先序遍历var prev *TreeNoderoot := tfor root != nil || len(s) > 0 {for root != nil {s = append(s, root)ret[0] = append(ret[0], root.Val)root = root.Left}root = s[len(s)-1].Rights = s[:len(s)-1]}// 中序遍历root = tfor root != nil || len(s) > 0 {for root != nil {s = append(s, root)root = root.Left}root = s[len(s)-1]s = s[:len(s)-1]ret[1] = append(ret[1], root.Val)root = root.Right}// 后序遍历root = tfor root != nil || len(s) > 0 {for root != nil {s = append(s, root)root = root.Left}root = s[len(s)-1]s = s[:len(s)-1]if root.Right == nil || root.Right == prev {ret[2] = append(ret[2], root.Val)prev = rootroot = nil} else {s = append(s, root)root = root.Right}}return ret}
Mirros算法: O(n) O(1)
//先序func preorderTraversal(root *TreeNode) (ret []int) {if root == nil {return nil}cur := rootfor cur != nil {mostRight := cur.Leftif mostRight != nil {for mostRight.Right != nil && mostRight.Right != cur {mostRight = mostRight.Right}if mostRight.Right == nil {mostRight.Right = curret = append(ret, cur.Val)cur = cur.Leftcontinue} else {mostRight.Right = nil}} else {ret = append(ret, cur.Val)}cur = cur.Right}return}
//中序func inorderTraversal(root *TreeNode) (ret []int) {if root == nil {return nil}cur := rootfor cur != nil {mostRight := cur.Leftif mostRight != nil {for mostRight.Right != nil && mostRight.Right != cur {mostRight = mostRight.Right}if mostRight.Right == nil {mostRight.Right = curcur = cur.Leftcontinue} else {mostRight.Right = nil}}ret = append(ret, cur.Val)cur = cur.Right}return}
//后序func reverse(a []int) {for i:=0; i<len(a)/2; i++ {a[i], a[len(a)-i-1] = a[len(a)-i-1], a[i]}}func postorderTraversal(root *TreeNode) (ret []int) {addPath := func (node *TreeNode) {resize := len(ret)for ; node != nil; node = node.Right {ret = append(ret, node.Val)}reverse(ret[resize:])}cur := rootfor cur != nil {mostRight := cur.Leftif mostRight != nil {for mostRight.Right != nil && mostRight.Right != cur {mostRight = mostRight.Right}if mostRight.Right == nil {mostRight.Right = curcur = cur.Leftcontinue} else {mostRight.Right = niladdPath(cur.Left)}}cur = cur.Right}addPath(root)return}
105. 从前序与中序遍历序列构造二叉树
时间复杂度:O(n),其中 n 是树中的节点个数。
空间复杂度:O(n),除去返回的答案需要的 O(n) 空间之外,我们还需要使用 O(n) 的空间存储哈希映射,以及 O(h)(其中 h 是树的高度)的空间表示递归时栈空间。这里 h < n,所以总空间复杂度为O(n)。
// 递归构建func buildTree(preorder []int, inorder []int) *TreeNode {if len(preorder)<=0 || len(inorder) <= 0 {return nil}root := &TreeNode{}root.Val = preorder[0]idx := 0for ; idx<len(inorder); idx++ {if inorder[idx] == root.Val {break}}root.Left = buildTree(preorder[1:idx+1], inorder[:idx])root.Right = buildTree(preorder[idx+1:], inorder[idx+1:])return root}
还有迭代方式:有点复杂,有空研究补充
106. 从中序与后序遍历序列构造二叉树
时间复杂度:O(n),其中 n 是树中的节点个数。
空间复杂度:O(n),除去返回的答案需要的 O(n) 空间之外,我们还需要使用 O(n) 的空间存储哈希映射,以及 O(h)(其中 h 是树的高度)的空间表示递归时栈空间。这里 h < n,所以总空间复杂度为O(n)。
// 递归方式func buildTree(inorder []int, postorder []int) *TreeNode {if len(postorder) == 0 {return nil}root := &TreeNode{postorder[len(postorder)-1], nil, nil}i := 0for ; i < len(inorder); i++ {if inorder[i] == postorder[len(postorder)-1] {break}}// 中序数组按后序最后一个数左右切分;后序数组按中序左右切片的长度划分,却掉最后一个root.Left = buildTree(inorder[:i], postorder[:i])root.Right = buildTree(inorder[i+1:], postorder[i:len(postorder)-1])return root}
还有迭代方式:有点复杂,有空研究补充
110. 平衡二叉树
解法1:自定向下递归 。先判断当前节点是否平衡,在判断左右子树是否平衡
时间复杂度:O(n ^ 2),其中 n 是二叉树中的节点个数。
最坏情况下,二叉树是满二叉树,需要遍历二叉树中的所有节点,时间复杂度是O(n)。
对于节点 p,如果它的高度是 d,则 height(p) 最多会被调用 d 次(即遍历到它的每一个祖先节点时)。对于平均的情况,一棵树的高度 h 满足O(h)=O(logn),因为 d≤h,所以总时间复杂度为O(nlogn)。对于最坏的情况,二叉树形成链式结构,高度为 O(n),此时总时间复杂度为 O(n^2)
空间复杂度:O(n),其中 n 是二叉树中的节点个数。空间复杂度主要取决于递归调用的层数,递归调用的层数最大不会超过 n
func isBalanced(root *TreeNode) bool {if root == nil {return true}return abs(height(root.Left) - height(root.Right)) <= 1 && isBalanced(root.Left) && isBalanced(root.Right)}func height(root *TreeNode) int {if root == nil {return 0}return max(height(root.Left), height(root.Right)) + 1}func max(a, b int) int {if a > b {return a}return b}func abs(a int) int {if a < 0 {return -1 * a}return a}
可以拿到offer的解法:
自底向上的递归:先判断左右子树是否平衡,再判断当前节点是否平衡
自底向上递归的做法类似于后序遍历,对于当前遍历到的节点,先递归地判断其左右子树是否平衡,再判断以当前节点为根的子树是否平衡。如果一棵子树是平衡的,则返回其高度(高度一定是非负整数),否则返回 -1−1。如果存在一棵子树不平衡,则整个二叉树一定不平衡。
func isBalanced(root *TreeNode) bool {if root == nil {return true}return height(root) >= 0}func height(root *TreeNode) int {if root == nil {return 0}leftHeight := height(root.Left)rightHeight := height(root.Right)if abs(leftHeight - rightHeight) > 1 || leftHeight == -1 || rightHeight == -1 {return -1}return max(leftHeight, rightHeight) + 1}func max(a, b int) int {if a > b {return a}return b}func abs(a int) int {if a < 0 {return -1 * a}return a}
5. 层序遍历
题目描述:给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。
示例:
输入:[1,2,3,4,5,null,7,8]
1/ \2 3/ \ \4 5 7/8
输出:[[1],[2,3],[4,5,7],[8]]
func listOfDepth(tree *TreeNode) []*ListNode {q := []*TreeNode{tree} // 层序队列ret := make([]*ListNode, 0)for len(q) > 0 {lhead := &ListNode{}cur := lheadp := []*TreeNode{} // 层序队列更新for j := 0; j < len(q); j++ {node := &ListNode{Val: q[j].Val, Next: nil}cur.Next = nodecur = nodeif q[j].Left != nil {p = append(p, q[j].Left)}if q[j].Right != nil {p = append(p, q[j].Right)}}ret = append(ret, lhead.Next)q = p}return ret}
6. 叶子统计
7. 最大二叉树 I
题目描述:给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下:
- 二叉树的根是数组中的最大元素。
- 左子树是通过数组中最大值左边部分构造出的最大二叉树。
- 右子树是通过数组中最大值右边部分构造出的最大二叉树。
- 通过给定的数组构建最大二叉树,并且输出这个树的根节点。
输入:[3,2,1,6,0,5]
输出:返回下面这棵树的根节点:
6/ \3 5\ /2 0\1
解法一:递归
时间O(n^2) 一共被调用 n 次。每次递归寻找根节点时,需要遍历当前索引范围内所有元素找出最大值。一般情况下,每次遍历的复杂度为 O(logn),总复杂度为 O(nlogn)。最坏的情况下,数组 nums 有序,总的复杂度为 O(n^2)。
空间 O(n)
func constructMaximumBinaryTree(nums []int) *TreeNode {if len(nums) == 0 {return nil}max, idx := nums[0], 0for i := 0; i < len(nums); i++ {if nums[i] > max {max = nums[i]idx = i}}node := &TreeNode{Val: max, Left: nil, Right: nil}node.Left = constructMaximumBinaryTree(nums[0:idx])node.Right = constructMaximumBinaryTree(nums[idx+1:])return node}
解法二:
- 依次插入,先选取首项为root。
- 接下来每一项:如果小于root,则插入root的右树(insertRight);如果大于root,则选取该点为新root,将原树变为新root的左树(reRoot)
- 实现insertRight与reRoot函数
时间O(n) 最坏n^2
func constructMaximumBinaryTree(nums []int) *TreeNode {if len(nums) == 0 {return nil}root := &TreeNode{Val: nums[0]}for _, num := range nums[1:] {root = insert(num, root)}return root}func insert(val int, root *TreeNode) *TreeNode {if val < root.Val {insertRight(val, root) // 插入右树return root}return reRoot(val, root)}// 插入root的右树// 对于右树路径上的节点,如果遇到小于该值的节点。将该值作为新节点,原节点作为新节点的左树func insertRight(val int, root *TreeNode) {cur := rootfor {if cur.Right != nil {if cur.Right.Val < val {cur.Right = reRoot(val, cur.Right)return}cur = cur.Right} else {cur.Right = &TreeNode{Val: val}return}}}// 修改根为新节点并将原树赋给新root的左节点func reRoot(val int, root *TreeNode) (node *TreeNode) {node = &TreeNode{Val: val, Left: nil, Right: nil}node.Left = rootreturn}
998. 最大二叉树 II
问题:向一颗最大二叉树中插入一个节点。
解题思路:复用上面 7. 最大二叉树 I 中的第二种解法,插入节点
代码略
589. N叉树的前序遍历
递归:
func preorder(root *Node) []int {if root == nil {return nil}ret := make([]int, 0)var f func (root *Node)f = func (root *Node) {ret = append(ret, root.Val)if root.Children == nil {return}for _, child := range root.Children {f(child)}}f(root)return ret}
迭代(用栈):
func preorder(root *Node) []int {if root == nil {return nil}var ret []intvar stack []*Nodestack = append(stack, root)for len(stack) > 0 {node := stack[len(stack)-1]stack = stack[:len(stack)-1]ret = append(ret, node.Val)for i := len(node.Children)-1; i >= 0; i-- {stack = append(stack, node.Children[i])}}return ret}
111. 二叉树的最小深度
递归
func minDepth(root *TreeNode) int {if root == nil {return 0}if root.Left == nil {return minDepth(root.Right)+1}if root.Right == nil {return minDepth(root.Left)+1}return min(minDepth(root.Left), minDepth(root.Right))+1}func min(a, b int) int {if a < b {return a}return b}
Mirrors算法:
func minDepth(root *TreeNode) int {if root == nil {return 0}minD := math.MaxInt32cur := rootcurL := 0for cur != nil {mostRight := cur.Leftif mostRight != nil {mostRightHeight := 1for mostRight.Right != nil && mostRight.Right != cur {mostRight = mostRight.RightmostRightHeight++}if mostRight.Right == nil {mostRight.Right = curcur = cur.LeftcurL++continue} else {mostRight.Right = nilif mostRight.Left == nil && minD > curL {minD = curL}curL -= mostRightHeight}} else {curL++}cur = cur.Right}RightHeight := 1for root.Right != nil {RightHeight++root = root.Right}if root.Left == nil && RightHeight < minD {minD = RightHeight}return minD}
104. 二叉树的最大深度(递归和bfs)
bfs 空间O(1)
func maxDepth(root *TreeNode) (ans int) {if root == nil {return 0}s := []*TreeNode{}s = append(s, root)for len(s) > 0 {siz := len(s)for siz > 0 {n := s[0]s = s[1:]if n.Left != nil {s = append(s, n.Left)}if n.Right != nil {s = append(s, n.Right)}siz--}ans++}return ans}
124. 二叉树中的最大路径和
// 在树上, 设 dp[C] 代表以当前节点为结尾的最大上升路径和,// 则我们需要对节点的左右子树做一个选择, 有// dp[C] = max(max(dp[L], 0), max(dp[R], 0)) + C.val// 式中, C,L,R 分别代指 当前节点、左子节点、右子节点。func maxPathSum(t *TreeNode) int {ans := math.MinInt32var dfs func (*TreeNode) intdfs = func (root *TreeNode) int {if root == nil {return 0}left := max(dfs(root.Left), 0)right := max(dfs(root.Right), 0)val := left + right + root.Valans = max(ans, val)return max(left, right) + root.Val}dfs(t)return ans}func max(a, b int) int {if a > b {return a}return b}
剑指Offer
剑指 Offer 26. 树的子结构
//递归判断 O(mn)func isSubStructure(A *TreeNode, B *TreeNode) bool {return (A != nil && B != nil) && (recur(A, B) || isSubStructure(A.Left, B) || isSubStructure(A.Right, B))}//递归判断当前节点开始的每一个节点是否相同,不同则falsefunc recur(A *TreeNode, B *TreeNode) bool {if B == nil {return true}if A == nil || A.Val != B.Val {return false}return recur(A.Left, B.Left) && recur(A.Right, B.Right)}
剑指 Offer 37. 序列化二叉树
class Codec:def serialize(self, root):if not root:return "[]"queue = collections.deque()queue.append(root)res = []while queue:node = queue.popleft()if node:res.append(str(node.val))queue.append(node.left)queue.append(node.right)else:res.append("null")return "[" + ','.join(res) + ']'def deserialize(self, data):if data == "[]":return Nonevals, i = data[1:-1].split(","), 1root = TreeNode(int(vals[0]))queue = collections.deque()queue.append(root)while queue:node = queue.popleft()if vals[i] != "null":node.left = TreeNode(int(vals[i]))queue.append(node.left)i += 1if vals[i] != "null":node.right = TreeNode(int(vals[i]))queue.append(node.right)i += 1return root
public class Codec {public String serialize(TreeNode root) {if (root == null) {return "[]";}Queue<TreeNode> q = new LinkedList<>();q.add(root);StringBuilder sb = new StringBuilder();sb.append("[");while (!q.isEmpty()) {TreeNode node = q.poll();if (node != null) {sb.append(node.val + ",");q.add(node.left);q.add(node.right);} else {sb.append("null,");}}sb.deleteCharAt(sb.length() - 1);sb.append("]");return sb.toString();}public TreeNode deserialize(String data) {if (data == "[]") {return null;}String[] vals = data.substring(1, data.length() - 1).split(",");TreeNode root = new TreeNode(Integer.parseInt(vals[0]));Queue<TreeNode> q = new LinkedList<>();q.add(root);int index = 1;while (!q.isEmpty()) {TreeNode node = q.poll();if (!vals[index].equals("null")) {node.left = new TreeNode(Integer.parseInt(vals[index]));q.add(node.left);}index++;if (!vals[index].equals("null")) {node.right = new TreeNode(Integer.parseInt(vals[index]));q.add(node.right);}index++;}return root;}}
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
class Solution {public:TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {if (root == NULL || root == p || root == q) {return root;}if (p->val < root->val && q->val < root->val) {return lowestCommonAncestor(root->left, p, q);} else if (p->val > root->val && q->val > root->val) {return lowestCommonAncestor(root->right, p, q);}return root;}};// 同理最远公共祖先// 未测试,估计正确class Solution {public:TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {if (root == NULL || root == p || root == q) {return root;}if (p->val < root->val && q->val > root->val) {return root;} else if (p->val < root->val && q->val < root->val) {return lowestCommonAncestor(root->left, p, q);} else if (p->val > root->val && q->val > root->val) {return lowestCommonAncestor(root->right, p, q);}return NULL;}};
剑指 Offer 68 - II. 二叉树的最近公共祖先
思路:dfs
class Solution {public:TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {if (root == NULL || root == p || root == q) return root;TreeNode* left = lowestCommonAncestor(root->left, p, q);TreeNode* right = lowestCommonAncestor(root->right, p, q);if (left == NULL) return right;if (right == NULL) return left;return root; // p, q 分布在root的两边}};
【未找到】多叉树的最近公共祖先
思路: 转化成两个链表的交点问题解决
