5.30 Tree Traversal + Tree manipulation
阿新 • • 發佈:2018-05-31
二叉樹 vid RR preorder In root ati tree lis
- Binary Tree Preorder Traversal
題目:對一棵二叉樹進行前序遍歷,並將結果存在一個List
public class Solution { public ArrayList<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> result = new ArrayList<Integer>(); // null or leaf if (root == null) { return result; } // Divide ArrayList<Integer> left = preorderTraversal(root.left); ArrayList<Integer> right = preorderTraversal(root.right); // Conquer result.add(root.val); result.addAll(left); result.addAll(right); return result; } }
5.30 Tree Traversal + Tree manipulation