94. Binary Tree Inorder Traversal

来源:互联网 发布:动画生成软件 编辑:程序博客网 时间:2024/05/23 01:22

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].

思路:和上题一样,还是不用递归,用stack实现

代码如下(已通过leetcode)

public static void inorder(List<Integer> list,TreeNode root) {
if(root==null) return;
Stack<TreeNode> stack=new Stack<TreeNode>();
while(root!=null||!stack.isEmpty()) {
while(root!=null) {
stack.push(root);
root=root.left;
}
root=stack.pop();
list.add(root.val);
root=root.right;
}
}

0 0
原创粉丝点击