Skip to content

二叉树的前序遍历 #2

Open

Description

@YalongYan

leetcode 题目地址: 二叉树的前序遍历

递归版

var preorderTraversal = function(root) {
   let res = []
   function fn (node) {
       if(node) {
           res.push(node.val)
       }
       if (node.left) {
           fn(node.left)
       }
       if (node.right) {
           fn(node.right)
       }
   }
   root && fn(root)
   return res
};

非递归版本

var preorderTraversal = function(root) {
   let res = []
   let arr = []
   if(root) {
       arr.push(root)
   }
   while(arr.length) {
       let n = arr.pop()
       res.push(n.val)
       if (n.right) {
           arr.push(n.right)
       }
       if (n.left) {
           arr.push(n.left)
       }
   }
   return res
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions