美文网首页数据结构和算法分析Leetcode
leecode刷题(28)-- 二叉树的前序遍历

leecode刷题(28)-- 二叉树的前序遍历

作者: 希希里之海 | 来源:发表于2019-05-06 15:21 被阅读0次

leecode刷题(28)-- 二叉树的前序遍历

二叉树的前序遍历

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

示例:

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

输出: [1,2,3]

思路

这道题我们用递归的思想很容易就能解出来。前序遍历,我们先处理根,之后是左子树,然后是右子树。

代码如下

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> preorderTraversal(TreeNode root) {
        if (root != null) {
            list.add(root.val);
            preorderTraversal(root.left);
            preorderTraversal(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 preorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        if root is not None:
            res = res + [root.val]
            res = res + self.preorderTraversal(root.left)
            res = res + self.preorderTraversal(root.right)
        return res

总结

两门语言的代码量差不多,用递归几行就能搞定,对比如下:

对比.png

相关文章

网友评论

    本文标题:leecode刷题(28)-- 二叉树的前序遍历

    本文链接:https://www.haomeiwen.com/subject/xrtdoqtx.html