zoukankan      html  css  js  c++  java
  • [LC] 144. Binary Tree Preorder Traversal

    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]

    Solution 1:
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def preorderTraversal(self, root: TreeNode) -> List[int]:
            stack, res = [], []
            if root is None:
                return res
            stack.append(root)
            while stack:
                cur = stack.pop()
                res.append(cur.val)
                if cur.right:
                    stack.append(cur.right)
                if cur.left:
                    stack.append(cur.left)
            return res

    Solution 2: 

    /**
     * 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> res = new ArrayList<>();
            if (root == null) {
                return res;
            }
            Deque<TreeNode> queue = new LinkedList<>();
            queue.offerFirst(root);
            while (!queue.isEmpty()) {
                TreeNode cur = queue.pollFirst();
                res.add(cur.val);
                if (cur.right != null) {
                    queue.offerFirst(cur.right);
                }
                if (cur.left != null) {
                    queue.offerFirst(cur.left);
                }
            }
            return res;
        }
    }
     
  • 相关阅读:
    jQuery实现每隔几条元素增加1条线的方法
    Unity3D for Mac 破解
    IOS
    Unity3D 动态地创建识别图
    Easy AR简单教程
    iOS对象(数组)转化为JSon字符串
    iOS对象(字典或数组)转化为JSon字符串
    iOS
    iOS 逆向
    ios-逆向 手把手安装最新版Theos
  • 原文地址:https://www.cnblogs.com/xuanlu/p/11697326.html
Copyright © 2011-2022 走看看