zoukankan      html  css  js  c++  java
  • leecode刷题(29)-- 二叉树的中序遍历

    leecode刷题(29)-- 二叉树的中序遍历

    二叉树的中序遍历

    给定一个二叉树,返回它的中序 遍历。

    示例:

    输入: [1,null,2,3]
       1
        
         2
        /
       3
    
    输出: [1,3,2]
    

    思路

    跟上一道题一样,用递归的思想很快就能解决。

    中序遍历:

    先处理左子树,然后是根,最后是右子树。

    代码如下

    Java 描述

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        List<Integer> list = new ArrayList();
        public List<Integer> inorderTraversal(TreeNode root) {
            if (root != null) {
                inorderTraversal(root.left);
                list.add(root.val);
                inorderTraversal(root.right);
            }
            return list;
        }
    }
    

    python 描述

    # 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 not None:
                res = res + self.inorderTraversal(root.left)
                res = res + [root.val]
                res = res + self.inorderTraversal(root.right)
            return res
    

    总结

    对比如下:

    对比.png

  • 相关阅读:
    打标签tag
    高阶函数
    anywhere执行时端口被占用Address already in use:8080解决方法
    时间戳常见转化
    generator(生成器)
    Promise详解(转载)
    在手机上预览自己的本地h5页面
    箭头函数中的this
    扩展运算符
    38.线程
  • 原文地址:https://www.cnblogs.com/weixuqin/p/10822219.html
Copyright © 2011-2022 走看看