Middle order traversal of binary trees
Given the root node of a binary tree, return its middle-order traversal.
Examples can be found on the LeetCode website.
Source: LeetCode link: leetcode-cn.com/problems/bi… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.
Solution one: recursion
Initialize a result set, result, and recursively process it in the following order:
- First, put the result of the left subtree of root node into result;
- Add the root value to result.
- Add the result of the root node’s right subtree to result;
- When root is empty, an empty result is returned.
Finally, result is returned, which is the result of the middle-order traversal of the tree.
import java.util.ArrayList;
import java.util.List;
public class LeetCode_094 {
public static List<Integer> inorderTraversal(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
List<Integer> result = new ArrayList<>();
result.addAll(inorderTraversal(root.left));
result.add(root.val);
result.addAll(inorderTraversal(root.right));
return result;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
for (Integer integer : inorderTraversal(root)) {
System.out.print(integer + ""); }}}Copy the code
【 Daily Message 】 Give yourself a hope every day, try not to worry about tomorrow, not sigh for yesterday, just for today better.