您的位置:首页 > 其它

144. Binary Tree Preorder Traversal

2016-04-09 14:17 381 查看
Given a binary tree, return the preorder traversal of its nodes' values.

For example:

Given binary tree
{1,#,2,3}
,

1
\
2
/
3


return
[1,2,3]
.

思路:普通递归的先序遍历就就不写了,下面给出一种非递归的先序遍历,用stack来实现

public static void preorder(List<Integer> list, TreeNode root) {

if (root == null)

return;

Stack<TreeNode> stack = new Stack<TreeNode>();

while (root != null || !stack.isEmpty()) {

while (root != null) {

list.add(root.val);

stack.push(root);

root = root.left;

}

root=stack.pop();

root=root.right;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: