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;
}
}

最新文章

  1. 完美解决 Linux 下 Sublime Text 中文输入
  2. 【Discuz】云平台服务:出了点小错,由于站点ID/通信KEY等关键信息丢失导致Discuz!云平台服务出现异常
  3. atitit.设计模式(2) -----查表模式/ command 总结
  4. Netty 4(一) zero copy
  5. 如何将DataTable转换成List&lt;T&gt;呢?
  6. Java基础知识强化之网络编程笔记10:TCP之客户端读取文本文件服务器控制台输出
  7. SetTimer的使用
  8. 【原创】Linux opensource-src-4.3.2.tar.gz的安装。
  9. SICP阅读笔记(一)
  10. Spark Mllib框架1
  11. 区分window8中 ie10 window phone8
  12. python3学习笔记11(函数)
  13. linux:终端常用命令 + vi命令修改文件及保存 方法
  14. LeetCode 965 Univalued Binary Tree 解题报告
  15. Cmd2001的毒瘤水题题解
  16. ZH奶酪:Ionic通过angularJS+tabs-item-hide实现自定义隐藏tab
  17. nodejs 服务器实现区分多客户端请求服务
  18. recvfrom WSAEFAULT 10014 的错误记录
  19. C#程序中SQL语句作为函数参数形式问题
  20. iOS小技巧 - 如何生成范围随机数

热门文章

  1. python基础一day3 字符串
  2. Gradle dependencies 依赖方式
  3. c++如何使用全局变量
  4. Java ArrayList中去掉相同的元素并保留相同元素中的最后一个
  5. docker运行时设置redis密码并替换redis默认的dump.rdb
  6. python 一些函数和类用法记录
  7. [CF] 219D Choosing Capital for Treeland
  8. SVN 初级教程
  9. 条款34:区分接口继承和实现继承(Different between inheritance of interface and inheritance of implemenation)
  10. 分分钟钟学会Python - 模块