递归算法
上一层的函数还没执行完就调用下一层,因此,当达到递归终止条件时,首先return的是最底层调用的函数
int Sum(int n) { if (n <= 1) //#1 return n; //#2 return n+Sum(n - 1); //#3 }
若n=10,则return 10 + Sum(9),接着return 10 + 9 + Sum(8)...
当n=1时,最底层return 1 给倒数第二层,
倒数第二层return 2 + 1 给倒数第三层...
最后返回的结果就是 10 + 9 + 8 + ... + 1 = 55
java递归算法遍历二叉树:
public class TreeNode { public int data; public TreeNode leftChild; public TreeNode rightChild;
public TreeNode(int data) { this.data = data; }
/** * 创建二叉树 * * @param list * @return */ public static TreeNode createBinaryTree(LinkedList<Integer> list) { TreeNode node = null; if (list == null || list.isEmpty()) { return null; } Integer data = list.removeFirst(); if (data != null) { node = new TreeNode(data); node.leftChild = createBinaryTree(list); node.rightChild = createBinaryTree(list); } return node; } public static void main(String[] args) { LinkedList<Integer> inputList1 = new LinkedList<> (Arrays.asList(1, 2, 3, null, null, 4, 5, null, 6, null, null, 7, null, null)); TreeNode treeNode = createBinaryTree(inputList1); System.out.println("前序遍历:"); preOrderTraveral(treeNode); System.out.println("\n" + "中序遍历:"); inOrderTraveral(treeNode); System.out.println("\n" + "后序遍历:"); postOrderTraveral(treeNode); } /** * 前序遍历 * * @param node */ public static void preOrderTraveral(TreeNode node) { if (node == null) { return; } System.out.print(node.data + " "); preOrderTraveral(node.leftChild); preOrderTraveral(node.rightChild); } /** * 中序遍历 * * @param node */ public static void inOrderTraveral(TreeNode node) { if (node == null) { return; } inOrderTraveral(node.leftChild); System.out.print(node.data + " "); inOrderTraveral(node.rightChild); } /** * 后续遍历 * * @param node */ public static void postOrderTraveral(TreeNode node) { if (node == null) { return; } postOrderTraveral(node.leftChild); postOrderTraveral(node.rightChild); System.out.print(node.data + " "); } }
本文来自博客园,作者:日月星宿,转载请注明原文链接:https://www.cnblogs.com/ryxxtd/p/16124064.html