本文主要是介绍前序中序后序遍历javascript,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
前序遍历
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
let result = []
if(!root) return result
var traversal = function(root,result){
if(!root) return
result.push(root.val)
traversal(root.left,result)
traversal(root.right,result)
}
traversal(root,result)
return result
};
后序遍历
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function(root) {
let result = []
if(!root) return result
var traversal = function(root,result){
if(!root) return
traversal(root.left,result)
traversal(root.right,result)
result.push(root.val)
}
traversal(root,result)
return result
};
中序遍历
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var postorderTraversal = function(root) {
let result = []
if(!root) return result
var traversal = function(root,result){
if(!root) return
traversal(root.left,result)
result.push(root.val)
traversal(root.right,result)
}
traversal(root,result)
return result
};
这篇关于前序中序后序遍历javascript的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!