BST Traversal

Prompt

Write three functions that take in a Binary Search Tree (BST) and an empty array, traverse the BST, add its nodes’ values to the input array, and return that array. The three functions should traverse the BST using the
in-order, pre-order, and post-order treetraversal techniques, respectively. If you’re unfamiliar with tree-traversal
techniques, we recommend watching the Conceptual Overview section of this question’s video explanation before starting to code.

Each BST node has an integer value , a left child node, and a right child node. A node is said to be a valid BST node if and only if it satises the BST property: its value is strictly greater than the values of every node to its left; its value is less than or equal to the values of every node to its right; and its children nodes are either valid
BST nodes themselves or None / null .

Sample Input

在这里插入图片描述

Sample Output

inOrderTraverse: [1, 2, 5, 5, 10, 15, 22]
preOrderTraverse: [10, 5, 2, 1, 5, 15, 22]
postOrderTraverse: [1, 2, 5, 5, 22, 15, 10]

Solution

import java.util.List;

class Program {
  public static List<Integer> inOrderTraverse(BST tree, List<Integer> array) {
		// O(n) time | O(h) 
		if (tree.left != null) {
			inOrderTraverse(tree.left, array);
		}
		array.add(tree.value);
		if (tree.right != null) {
			inOrderTraverse(tree.right, array);
		}
    return array;
  }

  public static List<Integer> preOrderTraverse(BST tree, List<Integer> array) {
		array.add(tree.value);
		if (tree.left != null) {
			preOrderTraverse(tree.left, array);
		}
		if (tree.right != null) {
			preOrderTraverse(tree.right, array);
		}
    return array;
  }

  public static List<Integer> postOrderTraverse(BST tree, List<Integer> array) {
		if (tree.left != null) {
			postOrderTraverse(tree.left, array);
		}
		if (tree.right != null) {
			postOrderTraverse(tree.right, array);
		}
		array.add(tree.value);
    return array;
  }

  static class BST {
    public int value;
    public BST left;
    public BST right;

    public BST(int value) {
      this.value = value;
    }
  }
}

How to Bug Free

谨慎输出条件

  • 层次遍历
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值