终止递归
1. 实现目标:js 编写递归方法 查找指定节点;
2. 需解决问题:找到所需节点后,递归不会终止,直到所有节点遍历完成后才会停止,会消耗性能
3. 解决方案:优化递归方法,在找到所需节点后,直接终止递归
4. 代码:
function TreeNode ( value, children = [ ] ) { this . value = value; this . children = children;
}
const root = new TreeNode ( 1 , [ new TreeNode ( 2 , [ new TreeNode ( 4 ) , new TreeNode ( 5 ) ] ) , new TreeNode ( 3 , [ new TreeNode ( 6 ) , new TreeNode ( 7 , [ new TreeNode ( 8 ) , new TreeNode ( 9 ) ] ) , ] ) ,
] ) ;
let result = null ;
function traverseTreeErr ( findVal, node = root ) { console. log ( "traverseTreeErr" , node) ; if ( node. value === findVal) { result = node; return ; } for ( let child of node. children) { traverseTreeErr ( findVal, child) ; }
}
traverseTreeErr ( 6 ) ;
console. log ( "traverseTreeErr.result" , result) ;
function traverseTree ( findVal, node = root ) { console. log ( "traverseTree" , node) ; if ( node. value === findVal) { return node; } for ( let child of node. children) { let result = traverseTree ( findVal, child) ; if ( result) { return result; } } return null ;
}
console. log ( "traverseTree.result" , traverseTree ( 6 ) ) ;
5. 效果图: