编程导航算法村第七关 | 二叉树的遍历
前序遍历(递归)
public List<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
preorder(root, result);
return result;
}
public void preorder(TreeNode root, List<Integer> result) {
if (root == null) {
return;
}
result.add(root.val);
preorder(root.left, result);
preorder(root.right, result);
}
前序遍历(迭代)
- 先迭代到树的最底层,左左端的元素,然后弹出栈,访问他的右节点
public List<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
if (result == null) {
return result;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
while (!stack.isEmpty() || node != null) {
while (node!= null) {
result.add(node.val);
stack.push(node);
node = node.left;
}
node = stack.pop();
node = node.right;
}
return result;
}
中序遍历(迭代)
public List<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
while (!stack.isEmpty() || node != null) {
while (node != null) {
stack.push(node);
node = node.left;
}
node = stack.pop();
result.add(node.val);
node = node.right;
}
return result;
}
后续遍历(反转法)
- 后续遍历相当于在前序遍历的基础上,先访问右节点再访问左节点,最后翻转
public List<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
while (!stack.isEmpty() || node != null) {
while (node != null) {
stack.push(node);
result.add(node.val);
node = node.right;
}
node = stack.pop();
node = node.left;
}
Collections.reverse(result);
return result;
}
文章来源地址https://www.toymoban.com/news/detail-624885.html
文章来源:https://www.toymoban.com/news/detail-624885.html
到了这里,关于编程导航算法村第七关 |二叉树的遍历的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!