leetCode 94.Binary Tree Inorder Traversal(二叉树中序遍历) 解题思路和方法
2017-07-16 09:05
316 查看
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?
confused what
>
read more on how binary tree is serialized on OJ.
思路:二叉树的中序遍历,是典型的递归算法。可是题目中建议非递归实现。所以还是有些思考的。
只是算是基础题。感觉是必须掌握的。
代码例如以下(递归实现):
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; } }
相关文章推荐
- leetCode 94.Binary Tree Inorder Traversal(二叉树中序遍历) 解题思路和方法
- leetCode 85.Maximal Rectangle (最大矩阵) 解题思路和方法
- leetCode 39.Combination Sum(组合总和) 解题思路和方法
- leetCode 45.Jump Game II (跳跃游戏) 解题思路和方法
- leetCode 52.N-Queens II (n皇后问题II) 解题思路和方法
- leetCode 64.Minimum Path Sum (最短路) 解题思路和方法
- leetCode 13.Roman to Integer (罗马数字转整形) 解题思路和方法
- leetCode 15. 3Sum (3数之和) 解题思路和方法
- leetCode 78.Subsets (子集) 解题思路和方法
- leetCode 111.Minimum Depth of Binary Tree(二叉树最小深度) 解题思路和方法
- leetCode 75.Sort Colors (颜色排序) 解题思路和方法
- leetCode 47.Permutations II (排列组合II) 解题思路和方法
- leetCode 27.Remove Element (删除元素) 解题思路和方法
- leetCode 41.First Missing Positive (第一个丢失的正数) 解题思路和方法
- leetCode 48.Rotate Image (旋转图像) 解题思路和方法
- leetCode 16.3Sum Closest (离给定值最近的三数之和) 解题思路和方法
- leetCode 79.Word Search (词搜索) 解题思路和方法
- leetCode 86.Partition List(分区链表) 解题思路和方法
- leetCode 47.Permutations II (排列组合II) 解题思路和方法
- leetCode 93.Restore IP Addresses (恢复IP地址) 解题思路和方法