Binary Tree Inorder Traversal
来源:互联网 发布:维普数据库论文查询 编辑:程序博客网 时间:2024/04/24 22:08
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?
思路:需要借助于栈,由于是中序遍历二叉树,从根节点的左边开始遍历二叉树,不断将结点加入栈,直到遍历到最左边的结点,弹出该结点,
- 如果该结点有右结点,再把该右结点作为子树根节点,也是从该子树根结点的左边开始遍历 ,直到遍历到最左边;
- 如果弹出的结点没有右结点,那么继续弹出结点,直到弹出的结点存在右结点,每弹出一个结点就加入到结果集中,直到栈为空。返回结果集即可。
/** * 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> result=new ArrayList<Integer>(); if(root==null) return result; Stack<TreeNode> stack=new Stack<TreeNode>(); TreeNode p=root; while(!stack.empty()||p!=null) { if(p!=null) { stack.push(p); p=p.left; } else { TreeNode node=stack.pop(); result.add(node.val); p=node.right; } } return result; }}
0 0
- 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
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal
- HDU2586 How far away ?(LCA模板题)
- OKHttp源码解析
- 常用函数源码
- iPhone的技术能力是如何领军业界的?
- win32收不到F10按键消息解决办法
- Binary Tree Inorder Traversal
- linux自动重启tomcat脚本
- 变量存储类型
- mysql B-tree和hash索引性能测试对比
- IM服务器架构实现畅想
- BZOJ3884 上帝与集合的正确用法
- POJ 3210 : Coins
- 6.25 被虐记 6 期末测试 变相求和
- 机器学习中的范数规则化之(二)核范数与规则项参数选择