二叉树的前序遍历 (Binary Tree Preorder Traversal)

 

思路:

// @Title: 二叉树的前序遍历 (Binary Tree Preorder Traversal)
// @Author: qisiii
// @Date: 2024-09-14 21:22:14
// @Runtime: 0 ms
// @Memory: 40.6 MB
// @comment: 
// @flag: 
/**
 * 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) {
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            result.add(node.val);
            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
        }
        return result;
    }

}

+++ title = “二叉树的前序遍历 (Binary Tree Preorder Traversal)” draft = false +++

思路:

// @Title: 二叉树的前序遍历 (Binary Tree Preorder Traversal)
// @Author: qisiii
// @Date: 2024-09-14 21:04:38
// @Runtime: 0 ms
// @Memory: 40.8 MB
// @comment: 
// @flag: 
/**
 * 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<>();
        sort(result,root);
        return result;
    }
    private void sort(List<Integer> result,TreeNode node){
        if(node!=null){
            result.add(node.val);
            sort(result,node.left);
            sort(result,node.right);
        }
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18