二叉树的遍历

二叉树节点定义

public class TreeNode {
int val;
TreeNode left;
TreeNode right; TreeNode() {}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}

LeeCode 144: 二叉树的前序遍历

题目描述

给你一棵二叉树的根节点 root ,返回其节点值的前序遍历

Java代码实现

递归实现
public List<Integer> preorderRecursive(TreeNode root) {
List<Integer> res = new ArrayList<>();
preorderRecursiveImpl(root, res);
return res;
} public void preorderRecursiveImpl(TreeNode root, List<Integer> res) {
if (root == null) {
return;
} res.add(root.val);
preorderRecursiveImpl(root.left, res);
preorderRecursiveImpl(root.right, res);
return;
}
迭代实现

递归实现本质上是维护了一个隐藏的栈结构,而在迭代时需要手动维护。

public List<Integer> preorderIterative(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
} Stack<TreeNode> stack = new Stack<>();
/**
* 添加顺序: 根 -> 左 -> 右
*/
while (root != null || !stack.isEmpty()) {
while (root != null) {
res.add(root.val);
stack.push(root);
root = root.left;
} root = stack.pop();
root = root.right;
} return res;
}
Morris 实现
public List<Integer> preorderMorris(TreeNode root) {
List<Integer> res = new ArrayList<>();
TreeNode cur = root;
TreeNode prev = null; while (cur != null) {
// 当前节点没有左子节点,则直接访问当前节点,并将指针指向右子节点
if (cur.left == null) {
res.add(cur.val);
cur = cur.right; // 通过 cur.right 返回父节点
continue;
} prev = cur.left; // 寻找当前节点左子节点的最右子结点
while (prev.right != null && prev.right != cur) {
prev = prev.right;
} if (prev.right == null) {
prev.right = cur;
res.add(cur.val); // 前序访问根节点
cur = cur.left;
}
else {
prev.right = null;
cur = cur.right;
}
} return res;
}

LeeCode 94: 二叉树的中序遍历

题目描述

给你一棵二叉树的根节点 root,返回其节点值的中序遍历

Java代码实现

递归实现
public List<Integer> inorderRecursive(TreeNode root) {
List<Integer> res = new ArrayList<>();
inorderRecursiveImpl(root, res);
return res;
} public void inorderRecursiveImpl(TreeNode root, List<Integer> res) {
if (root == null) {
return;
} inorderRecursiveImpl(root.left, res);
res.add(root.val);
inorderRecursiveImpl(root.right, res);
return;
}
迭代实现
public List<Integer> inorderIterative(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
} Stack<TreeNode> stack = new Stack<>();
/**
* 添加顺序: 左 -> 根 -> 右
*/
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
} root = stack.pop();
res.add(root.val);
root = root.right;
} return res;
}
Morris 实现

Morris实现的核心想法是找到当前节点的左子节点的最右子结点,即当前节点中序遍历的前一个节点。

public List<Integer> inorderMorris(TreeNode root) {
List<Integer> res = new ArrayList<>();
TreeNode cur = root;
TreeNode prev = null; while (cur != null) {
// 当前节点没有左子节点,则直接访问该节点,然后将指针指向右子结点
if (cur.left == null) {
res.add(cur.val);
cur = cur.right; // 通过 cur.right 返回父节点
continue;
} prev = cur.left; // 寻找当前节点左子节点的最右子结点,即中序遍历中当前节点的前一个节点
while (prev.right != null && prev.right != cur) {
prev = prev.right;
} if (prev.right == null) {
prev.right = cur;
cur = cur.left;
}
else {
prev.right = null;
res.add(cur.val); // 中序访问根节点
cur = cur.right;
}
} return res;
}

LeeCode 145: 二叉树的后序遍历

题目描述

给你一棵二叉树的根节点 root,返回其节点值的后序遍历

Java代码实现

递归实现
public List<Integer> postorderRecursive(TreeNode root) {
List<Integer> res = new ArrayList<>();
postorderRecursiveImpl(root, res);
return res;
} public void postorderRecursiveImpl(TreeNode root, List<Integer> res) {
if (root == null) {
return;
} postorderRecursiveImpl(root.left, res);
postorderRecursiveImpl(root.right, res);
res.add(root.val);
return;
}
迭代实现
public List<Integer> postorderIterative(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
} Stack<TreeNode> stack = new Stack<>();
TreeNode previous = null;
/**
* 添加顺序: 左 -> 右 -> 根
*/
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
} root = stack.pop();
// 若右子树为空 或 右子树已经访问过,则添加根节点值
if (root.right == null || root.right == previous) {
res.add(root.val);
previous = root;
root = null;
}
else {
stack.push(root);
root = root.right;
}
} return res;
}

LeeCode 102: 二叉树的层序遍历

题目描述

给你一棵二叉树的根节点 root,返回其节点值的层序遍历。(即逐层地从左到右访问所有节点)。

建立模型

  1. 这是一个广度优先搜索的问题,先遍历顶层所有节点,再往下遍历
  2. 使用一个队列来维护遍历的节点
  3. 使用变量size记录当前层节点个数

代码实现

public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
} // 使用基于双向链表实现的队列维护
Deque<TreeNode> deque = new LinkedList<>();
deque.offer(root); // 添加到队尾 while (!deque.isEmpty()) {
int size = deque.size();
List<Integer> temp = new ArrayList<>(); for (int i = 0; i < size; i++) {
TreeNode node = deque.poll(); // 从队首取出
temp.add(node.val); if (node.left != null) {
deque.offer(node.left);
} if (node.right != null) {
deque.offer(node.right);
}
} res.add(new ArrayList<>(temp));
} return res;
}

LeeCode 二叉树问题(一)的更多相关文章

  1. leecode刷题(30)-- 二叉树的后序遍历

    leecode刷题(30)-- 二叉树的后序遍历 二叉树的后序遍历 给定一个二叉树,返回它的 后序 遍历. 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [3,2,1] 思路 ...

  2. leecode刷题(29)-- 二叉树的中序遍历

    leecode刷题(29)-- 二叉树的中序遍历 二叉树的中序遍历 给定一个二叉树,返回它的中序 遍历. 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,3,2] 思路 跟 ...

  3. leecode刷题(28)-- 二叉树的前序遍历

    leecode刷题(28)-- 二叉树的前序遍历 二叉树的前序遍历 给定一个二叉树,返回它的 前序 遍历. 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,2,3] 思路 ...

  4. leecode刷题(24)-- 翻转二叉树

    leecode刷题(24)-- 翻转二叉树 翻转二叉树 翻转一棵二叉树. 示例: 输入: 4 / \ 2 7 / \ / \ 1 3 6 9 输出: 4 / \ 7 2 / \ / \ 9 6 3 1 ...

  5. Leecode刷题之旅-C语言/python-111二叉树的最小深度

    /* * @lc app=leetcode.cn id=111 lang=c * * [111] 二叉树的最小深度 * * https://leetcode-cn.com/problems/minim ...

  6. Leecode刷题之旅-C语言/python-104二叉树最大深度

    /* * @lc app=leetcode.cn id=104 lang=c * * [104] 二叉树的最大深度 * * https://leetcode-cn.com/problems/maxim ...

  7. Leecode刷题之旅-C语言/python-101对称二叉树

    /* * @lc app=leetcode.cn id=101 lang=c * * [101] 对称二叉树 * * https://leetcode-cn.com/problems/symmetri ...

  8. 路径和 二叉树 leecode

    题目不难,很快ac,纯粹靠手感.https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/ /** * Definition for bina ...

  9. leecode第二百三十六题(二叉树的最近公共祖先)

    /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode ...

  10. leecode第一百二十四题(二叉树中的最大路径和)

    /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode ...

随机推荐

  1. 基于Docker搭建Redis集群(主从集群)

    基于Docker搭建Redis集群(主从集群)   最近陆陆续续有不少园友加我好友咨询 redis 集群搭建的问题,我觉得一定是之前写的这篇 <基于Docker的Redis集群搭建> 文章 ...

  2. Hbase操作与编程使用

    1.任务: 列出HBase所有的表的相关信息,例如表名: 3. 编程完成以下指定功能(教材P92下): (1)createTable(String tableName, String[] fields ...

  3. CentOS 7(Linux)安装docker,执行yum install docker-io -y报错

    CentOS 7(Linux)安装Docker,执行yum install docker-io -y报错 一.执行yum install docker-io -y报错 Error: docker-ce ...

  4. 【组会】2023_1_27 google soli

    Soli: Ubiquitous Gesture Sensing with Millimeter Wave Radar (59) soli是一项运用微型雷达监测空中手势动作的传感技术,这种特殊设计的雷 ...

  5. win10edge浏览器个人账户退出登录后再次登录自动登录问题

    edge浏览器退出登录后,再次点击登录以同步数据会自动登录,可查看书签等个人数据 解决方法: 先在浏览器里面退出账户. 1.设置--电子邮件和账户--管理 2.登录后--安全--安全仪表板--高级安全 ...

  6. 解决com.alibaba.excel.exception.ExcelGenerateException: Can not close IO.

    我在使用easycel导出到zip包中时,出现了这个问题.各种文件输出时产生的问题其实大同小异 查看了一些网上的文章,还有github上关于此bug的issue,总算是理清并解决了. 解决方法一 主要 ...

  7. .Net中跨域问题的解决方案

    开发中前端与后端完全分离并分开发布,遇到跨域问题,一通百度之后,解决方案如下: 把下面的代码放在web.config文件中的 System.WebServer 节点下 <httpProtocol ...

  8. MAC下使用Wireshark调试chrome浏览器的HTTP/2流量

    1.设置环境变量 mkdir ~/tls && touch ~/tls/sslkeylog.log #zsh echo "\nexport SSLKEYLOGFILE=~/t ...

  9. windos 环境下载安装seata

    参考: https://blog.csdn.net/lianghecai52171314/article/details/127330916

  10. DRF的视图与路由集Routers

    一 视图 Django REST framwork 提供的视图的主要作用: 控制序列化器的执行(检验.保存.转换数据) 控制数据库模型的操作 一 普通视图APIView 一 两个视图基类 1 APIV ...