二叉树的结构定义
class TreeNode{
int val; // 定义根节点的值
TreeNode left; // 定义左子树
TreeNdoe right; // 定义右子树
public TreeNode(int val){
// 定义构造方法
this.val = val;
}
}
常见的算法
二叉树的层次遍历
给定一颗二叉树,返回其按层次遍历得到的节点值(逐层的,从左到右访问所有节点)
解题思路: 使用队列(Queue)来做,利用队列先进先出的
public List<List<Integer>> levelOrder(TreeNode root){
List<List<Integer>> lists = new ArrayList<>();
if(root == null) return lists;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int count = queue.size(); // 记录每一层节点的个数
List<Integer> list = new ArrayList<>();
while(count>0){
// 根据每一层节点的个数来遍历每一层
ListNode tmp = queue.poll();
list.add(tmp.val);
if(tmp.left!=null){
queue.offer(tmp.left);
}
if(tmp.right!=null){
queue.offer(tmp.right);
}
count--;
}
lists.add(list);
}
return lists;
}
二叉树的右视图
给定一颗二叉树,从右侧看,按照从顶部到底部的顺序,返回从顶部到底部能看到的值
解题思路:二叉树层次遍历的变形,每一层只添加最右边的那个值
public List<Integer> rightSideView(TreeNode root){
List<Integer> list = new ArrayList<>();
if(root == null) return list;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int count = queue.size();
while(count>0){
ListNode tmp = queue.poll();
if(count == 1){
// 当count=1时即为最后边的那个值
list.add(tmp.val);
}
if(tmp.left!=null){
queue.offer(tmp.left);
}
if(tmp.right!=null){
queue.offer(tmp.right);
}
count--;
}
}
return list;
}
二叉树前序遍历
给定一个二叉树,返回它前序遍历(非递归)
解题思路: 使用栈
public List<Integer> preorderTraversal(TreeNode root){
List<Integer> list = new ArrayList<>();
if(root == null) return list;
Stack<Integer> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode tmp = stack.pop();
list.add(tmp.val);
if(tmp.right!=null){
stack.push(tmp.right);
}
if(tmp.left!=null){
stack.push(tmp.left);
}
}
return list;
}
二叉树中序遍历
给定一个二叉树,返回它的中序遍历(非递归)
解题思路: 利用一个栈,当左节点存在时,就一直添加左节点,否则,出栈,同时将出栈节点的有节点压入栈中
public List

这篇博客详细介绍了在面试中常见的二叉树算法题目,包括二叉树的层次遍历、右视图、前序、中序、后序遍历,以及构造二叉树、路径总和、翻转、最近公共祖先、最大深度、直径、最大路径和等。还讨论了如何将有序数组转换为二叉搜索树和二叉搜索树的判定,同时涉及二叉树的序列化和反序列化问题。
最低0.47元/天 解锁文章
350

被折叠的 条评论
为什么被折叠?



