LeetCode Tree summary

Tree Summary

Definition for a binary tree node.

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

Binary Tree Traversal:

Pre-order/ In-order/ Post-order
以parent node顺序定义前序,中序或后序遍历。

  • pre-order:parent,left,right.
  • in-order:left,parent,right. binary search tree的中序遍历输出是排序过的!
  • post-order:left,right,parent.

Common tree problems 套路

包括one root/two root

Solution

  • recursion
  • time complexity = O(n) 每个node访问一次
  • space complexity = O(h) h是树的高度, best h = logn 树平衡, worst h = n 树不平衡

Template 1: one root

func solve(root): 
  if root == null : return ... 
  if f(root): return ...
  l = solve(root.left)
  r = solve(root.right)
  return g(root, l, r)

Template 2: two roots

func solve(p,q): 
  if p == null and q == null : return ... 
  if f(p, q): return ...
  c1 = solve(p.child, q.child) // child can be left or right, depends on the problem
  c2 = solve(p.child, q.child)
  return g(p, q, c1, c2)

Reference:
花花酱 LeetCode Trees 二叉树 - 刷题找工作 SP12

LeetCode tree problem Index

  • 94.[Medium] Binary Tree Inorder Traversal
  • 100.[Easy] Same Tree
  • 101.[Tree][Easy] Symmetric Tree
  • 104.[Tree][Easy] Maximum Depth of Binary Tree

Solution Summary

94. [Medium] Binary Tree Inorder Traversal

题目:二叉树中序遍历,返回一个数组。
solution 1:
递归
space: O(h), h为树高度,best case = logn,worst case = n
time: O(n) 每个node被访问一遍
solution 2 :
遍历, 用stack。借助pushAllLeft() 把节点的所有left child先放进stack。
space: O(logn), best case 当树为链表时 O(1)
time: O(n) 每个node被访问一遍

100.[Easy] Same Tree

题目:判断两个二叉树是否相同
solution 1:
递归。
注意 :判断root是否同时为空或其中一个为空。
solution 2:
遍历,用stack,把两个树分别push进两个stack,在pop时比较。

101.[Easy] Symmetric Tree

题目:判断两个二叉树是否对称
solution 1:
递归。写一个helper来比较左子树和右子树是否对称。
注意 :判断root空,以及root.left和root.right是否都为空或其中一个为空。
solution 2:
遍历。用两个stack来装左子树和右子树,左子树和右子树push进stack是顺序相反,pop()时比较,如果都相等就对称。
注意 :在while循环中要判断node为空和node左右子节点为空。

104.[Easy] Maximum Depth of Binary Tree

题目:求二叉树最大深度
solution 1:
递归
solution 2:
// Todo: iterative

你可能感兴趣的:(LeetCode Tree summary)