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

153 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

递归方式

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)