資料結構——二叉樹
阿新 • • 發佈:2021-08-05
二叉樹例項:
1
2 3
4 5
6
7 8
先序遍歷(根左右):12467835
中序遍歷(左根右):47682135
後序遍歷(左右根):78642531
遞迴實現遍歷:
前序
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {}8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 List<Integer> list = new ArrayList<>();18 public List<Integer> preorderTraversal(TreeNode root) { 19 if(root != null){ 20 list.add(root.val); 21 preorderTraversal(root.left); 22 preorderTraversal(root.right); 23 } 24 return list; 25 } 26 }
中序:
1 /** 2 * Definition for a binary tree node.3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 List<Integer> list = new ArrayList<Integer>(); 18 public List<Integer> inorderTraversal(TreeNode root) { 19 if(root != null){ 20 inorderTraversal(root.left); 21 list.add(root.val); 22 inorderTraversal(root.right); 23 } 24 return list; 25 } 26 }
後序:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 List<Integer> list = new ArrayList<>(); 18 public List<Integer> postorderTraversal(TreeNode root) { 19 if(root != null){ 20 postorderTraversal(root.left); 21 postorderTraversal(root.right); 22 list.add(root.val); 23 } 24 return list; 25 } 26 }