LeetCode-094-二叉樹的中序遍歷
阿新 • • 發佈:2021-01-12
示例:
輸入:root = [1,null,2,3]
輸出:[1,3,2]
解題思路
中序遍歷就是對一個節點來說,優先順序是遍歷左子節點,然後是自己本身,然後是右子節點
所以用遞迴可以很輕鬆寫出遍歷
inorder(root.left, result)
result.add(root.val)
inorder(root.right, result)
然後在遞迴的方法中使用一個集合儲存節點即可
程式碼
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new LinkedList<>();
inorder(root, result);
return result;
}
private void inorder(TreeNode root, List<Integer> result) {
if (root == null) {
return;
}
inorder(root.left, result);
result. add(root.val);
inorder(root.right, result);
}
}