zoukankan      html  css  js  c++  java
  • Leetcode 144. Binary Tree Preorder Traversal

    题目链接

    https://leetcode.com/problems/binary-tree-preorder-traversal/description/

    题目描述

    Given a binary tree, return the preorder traversal of its nodes' values.

    Example:

    Input: [1,null,2,3]
       1
        
         2
        /
       3
    
    Output: [1,2,3]
    

    Follow up: Recursive solution is trivial, could you do it iteratively?

    题解

    使用一个栈来保存数据,把每一个节点的子节点依次入栈,先右节点,再左节点。

    代码

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> list = new LinkedList<>();
            if (root == null) { return list; }
            Stack<TreeNode> s = new Stack<>();
            s.push(root);
            while (!s.isEmpty()) {
                TreeNode node = s.pop();
                list.add(node.val);
                if (node.right != null) { s.push(node.right); }
                if (node.left != null) { s.push(node.left); }
            }
            return list;
        }
    }
    
    
  • 相关阅读:
    随机生成300道四则运算
    练习
    电梯演说模板练习
    敏捷开发
    团队模式
    思考
    build to win 观后感
    四则运算
    Code review
    Mutual review
  • 原文地址:https://www.cnblogs.com/xiagnming/p/9603641.html
Copyright © 2011-2022 走看看