【LeetCode】144. 二叉樹的前序遍歷

題目描述

難度:【簡單】
標籤:【二叉樹】

給你二叉樹的根節點 root ,返回它節點值的 前序 遍歷。

題目地址:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/

示例

示例 1:

輸入:root = [1,null,2,3]
輸出:[1,2,3]

示例 2:

輸入:root = []
輸出:[]

示例 3:

輸入:root = [1]
輸出:[1]

示例 4:

輸入:root = [1,2]
輸出:[1,2]

示例 5:

輸入:root = [1,null,2]
輸出:[1,2]

題目大意

原生的二叉樹前序遍歷用法。
回顧下之前的筆記:【二叉樹的遍歷,前序、中序和後序】
https://www.cnblogs.com/pingguo-softwaretesting/p/14615248.html

解題

二叉樹的前序遍歷:按照訪問根節點——左子樹——右子樹的方式遍歷這棵樹,而在訪問左子樹或者右子樹的時候,我們按照同樣的方式遍歷,直到遍歷完整棵樹。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        preOrder(root, result);
        return result;
    }
    public void preOrder(TreeNode root, List<Integer> result) {
        if (root == null) {
            return;
        }
        result.add(root.val);
        preOrder(root.left, result);
        preOrder(root.right, result);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章