博主主页: 码农派大星. 关注博主带你了解更多数据结构知识 1.非递归的前序遍历 1.用栈来实现 2,前序遍历是根左右, 先是根节点入栈,,然后不为空时向左遍历,当为空时就返回向右遍历,右为空时直接出栈,依次循环即可. public void preOrderNot(TreeNode root){ Stack<TreeNode> stack = new Stack<>(); if(root==null){ return; } TreeNode cur = root; while (cur != null || !stack.isEmpty()){ while (cur != null){ stack.push(cur); System.out.print(cur.val + " "); cur = cur.left; } TreeNode top = stack.pop(); cur = top.right; } } 2.非递归的中序遍历 1和前序遍历不同的是,中序遍历是左根右 2先让左节点入栈,一直往左遍历,直到遇到空时,返回根节点,再向右一直遍历,遇到右为空时,出栈.
Is this you? As a journalist, you can create a free Muck Rack account to customize your profile, list your contact preferences, and upload a portfolio of your best work.
Claim your profile
Get in touch with return
Contact return, search articles and posts on X, monitor coverage, and track replies from one place.
Learn more about Muck Rack