zoukankan      html  css  js  c++  java
  • [LC] 94. Binary Tree Inorder Traversal

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

    Example:

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

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def inorderTraversal(self, root: TreeNode) -> List[int]:
            res = []
            if root is None:
                return res
            stack = []
            cur = root
            while cur or stack:
                while cur:
                    stack.append(cur)
                    cur = cur.left
                node = stack.pop()
                res.append(node.val)
                cur = node.right
            return res
                    
    
                
            
    /**
     * 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> inorderTraversal(TreeNode root) {
            LinkedList<TreeNode> stack = new LinkedList<>();
            List<Integer> res = new ArrayList<>();
            TreeNode cur = root;
            while (!stack.isEmpty() || cur != null) {
                if (cur != null) {
                    stack.offerFirst(cur);
                    cur = cur.left;
                } else {
                    cur = stack.pollFirst();
                    res.add(cur.val);
                    cur = cur.right;
                }
            }
            return res;
        }
    }
  • 相关阅读:
    web前端-----第二弹CSS
    web前端-----第一弹html
    mysql数据库第三弹
    mysql数据库第二弹
    mysql数据库第一弹
    django
    mysql基础
    面向对象进阶
    继承、多态、多态性
    面向对象的程序设计
  • 原文地址:https://www.cnblogs.com/xuanlu/p/11700656.html
Copyright © 2011-2022 走看看