leetcode--BinaryTreeInorderTraversal
2015-06-13 15:17
316 查看
二叉树中序遍历非递归实现:
利用两层循环以及stack,第一层循环代替总的递归过程,第二个循环代替先序遍历时逐层向下访问左节点。第一层循环用stack为空作为控制条件,第二层循环当前节点没有左节点就结束了。
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) return new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
List<Integer> list = new ArrayList<Integer>();
stack.push(root);
TreeNode current = root;
while (!stack.empty()) {
while (current != null) {
current = current.left;
if(current!=null)stack.push(current);
}
list.add(stack.peek().val);
if (stack.peek().right != null) {
current = stack.peek().right;
stack.pop();
stack.push(current);
}else stack.pop();
}
return list;
}
利用两层循环以及stack,第一层循环代替总的递归过程,第二个循环代替先序遍历时逐层向下访问左节点。第一层循环用stack为空作为控制条件,第二层循环当前节点没有左节点就结束了。
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) return new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
List<Integer> list = new ArrayList<Integer>();
stack.push(root);
TreeNode current = root;
while (!stack.empty()) {
while (current != null) {
current = current.left;
if(current!=null)stack.push(current);
}
list.add(stack.peek().val);
if (stack.peek().right != null) {
current = stack.peek().right;
stack.pop();
stack.push(current);
}else stack.pop();
}
return list;
}
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解
- LeetCode 2: Add Two Numbers (JAVA)
- LeetCode 1: Two Sum (JAVA)