您的位置:首页 > 编程语言 > Java开发

144. Binary Tree Preorder Traversal(Tree)

2016-07-18 00:17 357 查看
题目:

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

二叉树的前遍历,三种解法:

递归:

public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new LinkedList<Integer>();

return help(root,result);

}

List<Integer> help(TreeNode root,List<Integer> result)
{
if(root != null)
{
result.add(root.val);
result=help(root.left,result);
result=help(root.right,result);
}
return result;
}


栈:


采用栈模拟进行遍历,时间复杂度O(N),空间复杂度O(N):

public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new LinkedList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
if(root != null) stack.push(root);

while(!stack.isEmpty())
{
TreeNode temp = stack.pop();
result.add(temp.val);
if(temp.right!=null)stack.push(temp.right);
if(temp.left!=null)stack.push(temp.left);
}
return result;
}


Morris遍历法:


采用线索二叉树,将子节点右节点指向当前节点的前驱节点。时间复杂度O(N),空间复杂度O(1)

public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new LinkedList<Integer>();
TreeNode cur = root;

while(cur != null)
{
if(cur.left == null)
{
result.add(cur.val);
cur = cur.right;
}
else
{
//未线索化
TreeNode temp=cur.left;
while(temp.right!=null && temp.right!=cur)
{
temp=temp.right;
}

if(temp.right==null)
{
result.add(cur.val);
temp.right=cur;
cur=cur.left;
}
else
{
//线索化,清理线索
temp.right=null;
cur=cur.right;
}
}
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode java