二叉树前序遍历的思路
栈S;
p= root;
while(p || S不空){
while(p){
访问p节点;
p的右子树入S;
p = p的左子树;
}
p = S栈顶弹出;
}
前序遍历Leetcode地址:
https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
参考代码:
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
TreeNode cur = root;
Stack<TreeNode> stack = new Stack<>();
while (cur != null || !stack.empty()) {
while (cur != null) {
ans.add(cur.val);
stack.add(cur.right);
cur = cur.left;
}
cur = stack.pop();
}
return ans;
}
}
中序遍历思路
栈S;
p= root;
while(p || S不空){
while(p){
p入S;
p = p的左子树;
}
p = S.top 出栈;
访问p;
p = p的右子树;
}
Leetcode模板题:
https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
参考代码:
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
TreeNode cur = root;
Stack<TreeNode> stack = new Stack<>();
while (cur != null || !stack.empty()) {
while (cur != null) {
stack.add(cur);
cur = cur.left;
}
cur = stack.pop();
ans.add(cur.val);
cur = cur.right;
}
return ans;
}
}
后序遍历:
思路:
待续
参考前序遍历,前序遍历是 根左右,如果我们将压入栈的从右节点换成左节点,把第一轮搜索下去的从左节点换成右节点,那么可以得到,根右左 的序列,将其翻转,即可得到左右根