运行 ❯
获取您的
自己
网站
×
更改方向
更改主题,深色/浅色
前往 Spaces
Python
C
Java
class TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def inOrderTraversal(node): if node is None: return inOrderTraversal(node.left) print(node.data, end=", ") inOrderTraversal(node.right) root = TreeNode('R') nodeA = TreeNode('A') nodeB = TreeNode('B') nodeC = TreeNode('C') nodeD = TreeNode('D') nodeE = TreeNode('E') nodeF = TreeNode('F') nodeG = TreeNode('G') root.left = nodeA root.right = nodeB nodeA.left = nodeC nodeA.right = nodeD nodeB.left = nodeE nodeB.right = nodeF nodeF.left = nodeG # Traverse inOrderTraversal(root) #Python
#include <stdio.h> #include <stdlib.h> typedef struct TreeNode { char data; struct TreeNode* left; struct TreeNode* right; } TreeNode; TreeNode* createNewNode(char data) { TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode)); newNode->data = data; newNode->left = NULL; newNode->right = NULL; return newNode; } void inOrderTraversal(TreeNode* root) { if (root == NULL) { return; } inOrderTraversal(root->left); printf("%c, ", root->data); inOrderTraversal(root->right); } int main() { TreeNode* root = createNewNode('R'); TreeNode* nodeA = createNewNode('A'); TreeNode* nodeB = createNewNode('B'); TreeNode* nodeC = createNewNode('C'); TreeNode* nodeD = createNewNode('D'); TreeNode* nodeE = createNewNode('E'); TreeNode* nodeF = createNewNode('F'); TreeNode* nodeG = createNewNode('G'); root->left = nodeA; root->right = nodeB; nodeA->left = nodeC; nodeA->right = nodeD; nodeB->left = nodeE; nodeB->right = nodeF; nodeF->left = nodeG; // Traverse inOrderTraversal(root); free(nodeG); free(nodeF); free(nodeE); free(nodeB); free(nodeC); free(nodeD); free(nodeA); free(root); return 0; } //C
public class Main { public static class TreeNode { String data; TreeNode left; TreeNode right; public TreeNode(String data) { this.data = data; this.left = null; this.right = null; } } public static void inOrderTraversal(TreeNode node) { if (node == null) { return; } inOrderTraversal(node.left); System.out.print(node.data + ", "); inOrderTraversal(node.right); } public static void main(String[] args) { TreeNode root = new TreeNode("R"); TreeNode nodeA = new TreeNode("A"); TreeNode nodeB = new TreeNode("B"); TreeNode nodeC = new TreeNode("C"); TreeNode nodeD = new TreeNode("D"); TreeNode nodeE = new TreeNode("E"); TreeNode nodeF = new TreeNode("F"); TreeNode nodeG = new TreeNode("G"); root.left = nodeA; root.right = nodeB; nodeA.left = nodeC; nodeA.right = nodeD; nodeB.left = nodeE; nodeB.right = nodeF; nodeF.left = nodeG; // Traverse inOrderTraversal(root); } }
Python 结果
C 结果
Java 结果
C, A, D, R, E, B, G, F,
C, A, D, R, E, B, G, F,
C, A, D, R, E, B, G, F,