두 갈래 나무의 비귀속 범람과 귀속 범람
24263 단어 leetcode데이터 구조와 알고리즘
문서 목록
두 갈래 나무의 두루마리는 전 순서 두루마리, 중 순서 두루마리, 후속 순서 두루마리, 층 순서 두루마리가 있다.그런 다음 트리 노드의 정의는 다음과 같습니다.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
앞의 순서가 두루 미치다.
앞의 순서는 우리의 두 갈래 나무가 루트 노드를 먼저 훑어본 다음에 왼쪽 노드를 훑어보고 마지막은 오른쪽 노드를 훑어보는 것을 가리킨다
귀속
public void preOrder(TreeNode root){
if (root == null){
return;
}
//
System.out.println(root.val);
//
preOrder(root.left);
//
preOrder(root.right);
}
비귀속
public void preOrder(TreeNode root){
if (root == null){
return;
}
// , root.right , root.left
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()){
TreeNode node = stack.pop();
System.out.println(node.val);
if (node.right != null){
stack.push(node.right);
}
if (node.left != null){
stack.push(node.left);
}
}
}
중순으로 두루 다니다.
귀속
public void midOrder(TreeNode root){
if (root == null){
return;
}
//
preOrder(root.left);
//
System.out.println(root.val);
//
preOrder(root.right);
}
비귀속
public void midOrder(TreeNode root){
if (root == null){
return;
}
Stack<TreeNode> stack = new Stack<>();
do {
// ,
while (root != null){
stack.push(root);
root = root.left;
}
// , , ,
TreeNode node = stack.pop();
System.out.println(node.val);
if (node.right != null){
root = node.right;
}
}while (root!= null || !stack.isEmpty());
}
후순이 두루 다니다
귀속
public void afterOrder(TreeNode root){
if (root == null){
return;
}
//
preOrder(root.left);
//
preOrder(root.right);
//
System.out.println(root.val);
}
비귀속
public void afterOrder(TreeNode root){
if (root == null){
return;
}
// , root , root s2
Stack<TreeNode> s1 = new Stack<>();
Stack<TreeNode> s2 = new Stack<>();
s1.push(root);
while (!s1.isEmpty()){
TreeNode node = s1.pop();
if (node.left != null){
s1.push(node.left);
}
if (node.right != null){
s1.push(node.right);
}
s2.push(node);
}
while (!s2.isEmpty()){
System.out.println(s2.pop().val);
}
}
차례차례
층차 스트리밍은 두 갈래 나무의 노드를 층층이 스트리밍하는 것을 가리킨다. 여기서 나는 노드를list에 저장하고 BFS 방식으로 노드를 스트리밍한다고 가정한다.
public List<List<Integer>> levelOrder(TreeNode root) {
//
List<List<Integer>> lists = new ArrayList<>();
if (root == null){
return lists;
}
//
Queue<TreeNode> queue = new LinkedBlockingQueue<>();
queue.add(root);
while (!queue.isEmpty()){
List<Integer> list = new ArrayList<>();
int size = queue.size();
// , ,
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
list.add(node.val);
if (node.left != null){
queue.add(node.left);
}
if (node.right != null){
queue.add(node.right);
}
}
// list lists
lists.add(list);
}
return lists;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
0부터 시작하는 LeetCode Day8 「1302. Deepest Leaves Sum」해외에서는 엔지니어의 면접에 있어서 코딩 테스트라고 하는 것이 행해지는 것 같고, 많은 경우, 특정의 함수나 클래스를 주제에 따라 실장한다고 하는 것이 메인이다. 빠른 이야기가 본고장에서도 행해지고 있는 것 같은 코...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.