leetCode 94.Binary Tree Inorder Traversal(二叉树中序遍历) 解题思路和方法
2024-08-30 16:06:07
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1
\
2
/
3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
confused what "{1,#,2,3}"
means?
>
read more on how binary tree is serialized on OJ.
思路:二叉树的中序遍历,是典型的递归算法。可是题目中建议非递归实现。所以还是有些思考的。
只是算是基础题。感觉是必须掌握的。
代码例如以下(递归实现):
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<Integer> list = new ArrayList<Integer>();
public List<Integer> inorderTraversal(TreeNode root) {
/**
* 中序遍历,先左子树,再根,最后右子树
*/ if(root == null)
return list;
if(root.left != null){
inorderTraversal(root.left);
}
list.add(root.val);
if(root.right != null){
inorderTraversal(root.right);
}
return list;
}
}
非递归实现:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
/**
* 非递归实现中序遍历
* 中序遍历,先左子树,再根。最后右子树
*/ List<Integer> list = new ArrayList<Integer>(); if(root == null)
return list; TreeNode p = root;
Stack<TreeNode> st = new Stack<>(); while(p != null || !st.isEmpty()){
if(p != null){
st.push(p);
p = p.left;
}else{
p = st.pop();
list.add(p.val);
p = p.right;
}
}
return list;
}
}
最新文章
- 完美解决 Linux 下 Sublime Text 中文输入
- 【Discuz】云平台服务:出了点小错,由于站点ID/通信KEY等关键信息丢失导致Discuz!云平台服务出现异常
- atitit.设计模式(2) -----查表模式/ command 总结
- Netty 4(一) zero copy
- 如何将DataTable转换成List<;T>;呢?
- Java基础知识强化之网络编程笔记10:TCP之客户端读取文本文件服务器控制台输出
- SetTimer的使用
- 【原创】Linux opensource-src-4.3.2.tar.gz的安装。
- SICP阅读笔记(一)
- Spark Mllib框架1
- 区分window8中 ie10 window phone8
- python3学习笔记11(函数)
- linux:终端常用命令 + vi命令修改文件及保存 方法
- LeetCode 965 Univalued Binary Tree 解题报告
- Cmd2001的毒瘤水题题解
- ZH奶酪:Ionic通过angularJS+tabs-item-hide实现自定义隐藏tab
- nodejs 服务器实现区分多客户端请求服务
- recvfrom WSAEFAULT 10014 的错误记录
- C#程序中SQL语句作为函数参数形式问题
- iOS小技巧 - 如何生成范围随机数
热门文章
- python基础一day3 字符串
- Gradle dependencies 依赖方式
- c++如何使用全局变量
- Java ArrayList中去掉相同的元素并保留相同元素中的最后一个
- docker运行时设置redis密码并替换redis默认的dump.rdb
- python 一些函数和类用法记录
- [CF] 219D Choosing Capital for Treeland
- SVN 初级教程
- 条款34:区分接口继承和实现继承(Different between inheritance of interface and inheritance of implemenation)
- 分分钟钟学会Python - 模块