二叉樹--前序排列
阿新 • • 發佈:2021-01-01
前序排列:根左右,從主根開始
//遞迴
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; }