面试算法:二叉树


一、什么是二叉树?

二叉树是一棵空树,或者是一棵由一个根节点和两棵互不相交的,分别称作根的左子树和右子树组成的非空树;左子树和右子树又同样都是二叉树


二、遍历

1. Depth First Traversals

  • 先序遍历 Pre-order

    1. Visit the root.
    2. Traverse the left subtree, i.e., call Preorder(left-subtree)
    3. Traverse the right subtree, i.e., call Preorder(right-subtree)
  • 中序遍历 In-order

    1. Traverse the left subtree, i.e., call Inorder(left-subtree)
    2. Visit the root.
    3. Traverse the right subtree, i.e., call Inorder(right-subtree)
  • 后序遍历 Post-order

    1. Traverse the left subtree, i.e., call Postorder(left-subtree)
    2. Traverse the right subtree, i.e., call Postorder(right-subtree)
    3. Visit the root.

2. Breadth First or Level Order Traversal


三、三种二叉树题型

1. 求值

从二叉树中求子数的值(depth, average, sum, lowest common ancestor, path)。
使用分治法,把左子树的值和右子树的值通过递归,传递给根节点。
有两种传递的方式:

  • Return Value / Class (新建一个class来return多个值)
class ResultType {
    ...;
    ...;
    public ResultType(...) {
        ...
    }
}
private ResultType helper(TreeNode root) {
	if (root == null) {
		return new ResultType(...);
    }
    ResultType left = helper(root.left);
    ResultType right = helper(root.right);
    
    if (left...right) {
    	return new ResultType(...);
    }
    if (left...right) {
        return new ResultType(...);
    }
    
    return new ResultType(...);
}
  • Parameter (通过parameter把值传递给caller)
private void foo(TreeNode node, List<> list) {
   if (node.left == null && node.right == null) {
   	list.add(...);
   	return;
   }
   if (node.left != null) {
   	foo(node.left, list);
   }
   if (node.right != null) {
   	foo(node.right, , list);
   }
}

2. 结构变换

一般涉及到二叉树翻转,变成list或者string。
没有固定模版,根据情况使用BFS/DFS来解决。

3. 搜索

只需要记一个模版即可:
binary search tree iterator
先从根结点遍历二叉树搜索出一个起始点,然后用binary search tree iterator来搜就行。

四、题目

https://blog.csdn.net/Kejonho/article/details/109759581

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值