前序排列:根左右,从主根开始
//递归
public static void preOrder(TreeNode root){
if(root != null){
Sysout.out.println(root.data + "");
preOrder(root.lchild);
preOrder(root.rchild);
}
}
//前序遍历---非递归
Stack<TreeNode> stack = new Stack<>();
List<TreeNode> list = new ArrayList<>();
public List<TreeNode> preOrder(TreeNode root){
while(root!=null || !stack.isEmpty()){
while(root!=null){
list.add(root);
stack.push(root);
root=root.left;
}
TreeNode node = stack.pop();
root = node.right;
}
return list;
}
本文介绍了如何使用递归和非递归两种方法实现二叉树的前序遍历。递归方法直接从根节点开始,然后遍历左子树和右子树;非递归方法利用栈来模拟递归过程,先将根节点入栈,接着处理左子树,当栈不为空或当前节点不为null时,出栈并访问节点,然后转向其右子节点。这两种方法都是数据结构和算法中常见的操作。
1246

被折叠的 条评论
为什么被折叠?



