二叉树是一种非常重要的数据结构,很多其它数据结构都是基于二叉树的基础演变而来的。对于二叉树,有深度遍历和广度遍历,深度遍历有前序、中序以及后序三种遍历方法,广度遍历即我们平常所说的层次遍历。因为树的定义本身就是递归定义,因此采用递归的方法去实现树的三种遍历不仅容易理解而且代码很简洁,而对于广度遍历来说,需要其他数据结构的支撑,比如堆了。所以,对于一段代码来说,可读性有时候要比代码本身的效率要重要的多。
树的最大深度

class Tree:
def __init__(self, node):
self.node = node
self.right = None
self.left = None
def __str__(self):
return str(self.node)
class Solution:
def maxDepth(self, root):
if root is None:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
四种主要的遍历思想为:
前序遍历:根结点 ---> 左子树 ---> 右子树
中序遍历:左子树---> 根结点 ---> 右子树
后序遍历:左子树 ---> 右子树 ---> 根结点
层次遍历:只需按层次遍历即可
前序遍历
java
public void preOrderTraverse1(TreeNode root) {
if (root != null) {
System.out.print(root.val+" ");
preOrderTraverse1(root.left);
preOrderTraverse1(root.right);
}python
def preorder(root):
if not root: //为空返回,递归出口
return
print(root.val)
preorder(root.left)
preorder(root.right)
中序遍历

public void inorder1(TreeNode root){
public List<Integer> list = new ArrayList<>();
if(root != null){
inorder(root.left); //左--根--右
list.add(root.val);
inorder(root.right);
}
}
def inOrder(self, root): #左--根--右
if not root:
return
self.inOrder(root.left)
print(root)
self.inOrder(root.right)
后序遍历
即 左--右--根
















