先序遍历(递归及非递归)

public classPreOrderBT {

publicArrayListresult=newArrayList<>();

publicArrayListpre=newArrayList<>();

public voidpreOrder(TreeNode root){

if(root ==null){

return;

}

//访问根->左孩子->右孩子

result.add(root.val);

preOrder(root.left);

preOrder(root.right);

}

// no recursion

public voidpreOrderTraversal(TreeNode root)

{

if(root ==null){

return;

}

Stack stack =newStack();

stack.push(root);

while(!stack.isEmpty()){

TreeNode node = stack.pop();

pre.add(node.val);

if(node.right!=null){

stack.push(node.right);

}

if(node.left!=null){

stack.push(node.left);

}

}

}

}

你可能感兴趣的:(先序遍历(递归及非递归))