LeetCode 94. Binary Tree Inorder Traversal
2016-02-22 19:04
417 查看
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree
return
Note: Recursive solution is trivial, could you do it iteratively?
分析:中序遍历的顺序是左右根,用堆栈迭代的方法模拟递归实现,堆栈用LinkedList实现
如果当前结点不为null,则压入堆栈,然后继续观察其左孩子;如果没有左孩子,则弹出堆栈中第一个数据,观察其右孩子。
代码:
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?
分析:中序遍历的顺序是左右根,用堆栈迭代的方法模拟递归实现,堆栈用LinkedList实现
如果当前结点不为null,则压入堆栈,然后继续观察其左孩子;如果没有左孩子,则弹出堆栈中第一个数据,观察其右孩子。
代码:
/** * 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> listVal = new ArrayList<Integer>(); LinkedList<TreeNode> listNode = new LinkedList<TreeNode>(); if(root == null) return listVal; TreeNode p = root; while(!listNode.isEmpty() || p != null){ if(p != null){ listNode.push(p); p = p.left; continue; } TreeNode t = listNode.pop();// listVal.add(t.val); p = t.right; } return listVal; } }
相关文章推荐
- jQuery和ExtJS的timeOut超时问题和event事件处理问题
- install wine on ubuntu
- 谁有(爱普生R290维修程序)
- 给大一学生:让积累说话
- mySQL相关函数的使用
- UVAOJ 821 Page Hopping(最短路)
- 性能测试(二):性能测试的分析步骤
- jquery的delegate实现原理
- a kind of programming font on linux -- Inconsolata
- 函数名和数组名最大的区别
- docker
- 坐标和依赖
- ActiveX(五)更好的“ActiveX”?
- ZOJ 3870 Team Formation
- C++ primer阅读笔记之标准库vector类型学习
- 在hadoop 的任务中设置 map数量
- android开发 框架
- ZOJ 3212 K-Nice(构造)
- 蓝桥杯-杨辉三角形(BASIC)
- LaTeX中字体加黑命令的使用方法