博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Binary Tree Inorder Traversal
阅读量:4099 次
发布时间:2019-05-25

本文共 1199 字,大约阅读时间需要 3 分钟。

题目地址:

Given a binary tree, return the inorder traversal of its nodes’ values.

For example:

Given binary tree [1,null,2,3],

1    \     2    /   3

return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

既然不让用递归,那就只能用堆栈了。

public class BinaryTreeInorderTraversal {
public static List
inorderTraversal(TreeNode root) { List
res = new ArrayList<>(); if (root == null) return res; Stack
stack = new Stack<>(); TreeNode node = root; while (node != null) { stack.push(node); node = node.left; } while (!stack.isEmpty()) { node = stack.pop(); res.add(node.val); if (node.right != null) { node = node.right; while (node != null) { stack.push(node); node = node.left; } } } return res; } public static void main(String[] args) { TreeNode root = new TreeNode(1); root.right = new TreeNode(2); root.right.left = new TreeNode(3); System.out.println(inorderTraversal(root)); return; }}

转载地址:http://gihii.baihongyu.com/

你可能感兴趣的文章
Java的新未来:逐渐“Kotlin化”
查看>>
Java反射是什么?看这篇绝对会了!
查看>>
京东T9用一份900页SpringBoot笔记让你像搭积木一样构建系统架构
查看>>
目前开发中爆火的Java、Go和Rust间的比较!
查看>>
Java语言新特性?封印类
查看>>
MySQL深度解析,基础+高级篇数据库教程-从入门到入坟
查看>>
全网最全SpringBoot干货知识总结(超详细,建议收藏)
查看>>
同事牛逼啊,写了个隐藏 bug,我排查了 3 天才解决问题
查看>>
凭借这份文档,阿里Java岗四面直接定级P8,面经面试题分享
查看>>
Spring Boot在微服务中的最佳实践
查看>>
请把 .gitattributes 加到你的 Git 仓库中
查看>>
太赞了!美团T9终于整理出Java架构之完美设计实战开源文档
查看>>
一篇文章让你了解基于Spring的测试
查看>>
10个微服务架构设计的最佳实践
查看>>
分布式ID生成策略,我和面试官掰扯了一个小时
查看>>
逆袭大厂之路——Java程序员必备金九银十跳槽面试涨薪秘籍
查看>>
清华架构师熬夜整理,带你走进Kafka消息中间件
查看>>
GitHub上标星120k的Java进阶面试教程等!(建议收藏)
查看>>
为什么说Java程序员到了必须掌握SpringBoot的时候
查看>>
基于Rust-vmm实现Kubernetes运行时
查看>>