leetcode_94_Binary Tree Inorder Traversal
来源:互联网 发布:1元域名注册 编辑:程序博客网 时间:2024/06/03 15:52
1.描述
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?
2.思路
a.先遍历左子树直至左孩子为空
b.然后看当前节点的右子树是否为空,为空,则访问当前节点,弹出当前节点,重新判断;不为空,访问当前节点,然后将当前节点弹出,并将当前节点的右孩子进栈,返回a
c.这中间需要注意的是,在弹出当前节点后,在获得栈顶的当前节点前先判断下栈是否为空
3.代码
public List<Integer> inorderTraversal(TreeNode root) { List<Integer>list=new ArrayList<Integer>(); if(root==null) return list; Stack<TreeNode>st=new Stack<TreeNode>(); st.push(root); TreeNode top=null; while(!st.empty()) { top=st.peek(); while(top.left!=null) { st.push(top.left); top=top.left; } while(top.right==null) { list.add(top.val); st.pop(); if(!st.empty()) top=st.peek(); else break; } if(!st.empty()) { list.add(top.val); st.pop(); st.push(top.right); } } return list; }
4.结果
0 0
- Leetcode_94_Binary Tree Inorder Traversal
- leetcode_94_Binary Tree Inorder Traversal
- leetcode_94_Binary Tree Inorder Traversal
- Leetcode_94_Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- STL 适配器
- KMP字符串模式匹配详解
- JUnit 运行参数化测试简单入门
- 使用Packet.dll和npf.sys实现原始数据包的发送和接收
- 机器学习中的数学(1)-回归(regression)、梯度下降(gradient descent)
- leetcode_94_Binary Tree Inorder Traversal
- HDU 2044 一只小蜜蜂
- AngularJS $on、$emit和$broadcast简单功能实例
- Lisp学习5
- Mac OS X Yosemite安装Hadoop 2.6记录
- C++开源项目
- hdu4549---M斐波那契数列(矩阵+欧拉定理)
- c++ string 类基本用法
- ZOJ 2107 HDU 1007 Quoit Design(最近点对)