阅读 108

数据结构—递归和迭代两种方式求树结点之和

递归方式

dfs_sum.png

首先我们想递归方法,这里退出条件节点为空,也就是 base 条件,当节点为 null 这返回 0  退出递归,我们给每一个叶子节点都添加左右子节点,设定为 null 如上图第一个图中所有浅灰色的结点表示。

然后当遍历到为 null 就退出递归,那么层的逻辑又是什么,逻辑就是将一个结点的左子结点值加上右子结点值以及当前结点值的和将其返回。

const treeSum = (root)=>{     if(root === null) return 0;     return root.val + (treeSum(root.left) + treeSum(root.right)); } 复制代码

迭代方式

思路和递归基本一致,这里引入一个队列,队列也就是层级迭代,首先将根结点加入队列,然后在迭代将队列值出列后将其值加入求和值,然后在判断其左右子结点是否存在,如果存在将子结点入队。直到队列清空退出迭代。

const treeSumWithIterator = (root)=>{     if(root === null) return 0;     let total = 0;     let queue = [ root ]     while(queue.length > 0){         const currentNode = queue.shift()         total += currentNode.val         if(currentNode.left != null) queue.push(currentNode.left)         if(currentNode.right != null) queue.push(currentNode.right)     }     return total } 复制代码

完整代码

class Node{     constructor(val){         this.val = val;         this.left = null;         this.right = null;     } } const a = new Node(3); const b = new Node(11); const c = new Node(4); const d = new Node(4); const e = new Node(2); const f = new Node(1); a.left = b; a.right = c; b.left = d; b.right = e; c.right = f; const treeSum = (root)=>{     if(root === null) return 0;     return root.val + (treeSum(root.left) + treeSum(root.right)); } const sum = treeSum(a) console.log(sum) const treeSumWithIterator = (root)=>{     if(root === null) return 0;     let total = 0;     let queue = [ root ]     while(queue.length > 0){         const currentNode = queue.shift()         total += currentNode.val         if(currentNode.left != null) queue.push(currentNode.left)         if(currentNode.right != null) queue.push(currentNode.right)     }     return total } const sum2 = treeSumWithIterator(a) console.log(sum2) 复制代码

最后给大家分享一道相关的问题,求树中的最小值,下面列出一种方式。

找树中的最小值

dfs_min.png

const treeMinValue = (root)=>{     let minValue = Infinity;     const stack = [ root ];     while(stack.length > 0){         const currentNode = stack.pop();         if(currentNode.val < minValue) minValue = currentNode.val         if(currentNode.left != null) stack.push(currentNode.left)         if(currentNode.right != null) stack.push(currentNode.right)     }     return minValue } const minVal = treeMinValue(a) console.log(minVal)


作者:ti138729
链接:https://juejin.cn/post/7021086244201299998

文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐