LeetCode树与图
Ban
ChangAn University二叉树
二叉树基础
二叉树前序遍历
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/*
前序遍历
*/
void preorder_print(TreeNode *node, int layer)
{
if (!node)
{
return;
}
for (int i = 0; i < layer; i++)
{
printf("-----");
}
printf("[%d]\n", node->val);
preorder_print(node->left, layer + 1);
preorder_print(node->right, layer + 1);
}
int main()
{
TreeNode a(1);
TreeNode b(2);
TreeNode c(5);
TreeNode d(3);
TreeNode e(4);
TreeNode f(6);
a.left = &b;
a.right = &c;
b.left = &d;
b.right = &e;
c.right = &f;
preorder_print(&a, 0);
return 0;
}
//java code
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
class Test {
public static void preorderPrint(TreeNode node, int layer) {
if (node == null) {
return;
}
for (int i = 0; i < layer; i++) {
System.out.print("-----");
}
System.out.format("[%d]\n", node.val);
preorderPrint(node.left, ++layer);
preorderPrint(node.right, ++layer);
}
public static void main(String[] args) {
TreeNode a = new TreeNode(1);
TreeNode b = new TreeNode(2);
TreeNode c = new TreeNode(5);
TreeNode d = new TreeNode(3);
TreeNode e = new TreeNode(4);
TreeNode f = new TreeNode(6);
a.left = b;
a.right = c;
b.left = d;
b.right = e;
c.right = f;
preorderPrint(a, 0);
}
}
//伪代码
//中序
preOrderPrint(node.left, ++layer);
System.out.format("[%d]\n", node.val);
preOrderPrint(node.right, ++layer);
//后序
preOrderPrint(node.left, ++layer);
preOrderPrint(node.right, ++layer);
System.out.format("[%d]\n", node.val);