Leetcode Binary Tree Inorder Traversal 二叉树中序遍历
2015-05-11 18:54
381 查看
题目:
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?
分析:
中序遍历的顺序是左中右。由于左子树遍历完才能遍历根节点,所以需要使用栈来存放有左子树的根节点。1. 找到树中最左边的节点,经过的节点全部压入栈
2. 弹栈,访问栈顶的节点,并将其右孩子压入栈中
3. 顺着栈顶节点的左子树向下,路过的节点全部如栈
4. 重复步骤2 3的过程
Java代码实现:
/*** 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> s = new Stack<TreeNode>();
s.push(root);
while(s.peek().left!=null)
s.push(s.peek().left);
while(!s.isEmpty())
{
TreeNode node = s.pop();
result.add(node.val);
if(node.right!=null)
{
s.push(node.right);
while(s.peek().left!=null)
s.push(s.peek().left);
}
}
return result;
}
}
相关文章推荐
- LeetCode:94_Binary Tree Inorder Traversal | 二叉树中序遍历 | Medium
- LeetCode 94 Binary Tree Inorder Traversal(二叉树中序遍历)
- 【LeetCode-面试算法经典-Java实现】【094-Binary Tree Inorder Traversal(二叉树中序遍历)】
- Leetcode: Binary Tree Inorder Traversal(二叉树中序遍历)
- Leetcode 94:Binary Tree Inorder Traversal (二叉树中序遍历,非递归)
- 【LeetCode】Binary Tree Inorder Traversal ---二叉树中序遍历
- 【LeetCode】Binary Tree Inorder Traversal 二叉树中序遍历递归以及非递归算法
- leetcode -day23 Construct Binary Tree from Inorder and Postorder Traversal & Construct Binary Tree f
- LeetCode之Binary Tree Inorder Traversal
- 【leetcode】105. Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode:Construct Binary Tree from Preorder and Inorder Traversal
- [线索二叉树] [LeetCode] 不需要栈或者别的辅助空间,完成二叉树的中序遍历。题:Recover Binary Search Tree,Binary Tree Inorder Traversal
- leetcode---Binary Tree Inorder Traversal---中序遍历
- LeetCode: Binary Tree Inorder Traversal [094]
- [LeetCode]Binary Tree Inorder Traversal
- [leetcode] Binary Tree Inorder Traversal
- Leetcode #106 Construct Binary Tree from Inorder and Postorder Traversal
- 【Leetcode】Construct Binary Tree From Inorder and Preorder/Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- leetcode Construct Binary Tree from Inorder and Postorder Traversal