牛客ONT45 距离是K的二叉树节点【中等 宽度优先遍历 Java/Go/PHP/C++】

题目

在这里插入图片描述
题目链接:
https://www.nowcoder.com/practice/e280b9b5aabd42c9b36831e522485622

思路

 图,队列
构件图,直接从target出发,扩展到第k层就是答案

Java代码

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param root TreeNode类
     * @param target int整型
     * @param k int整型
     * @return int整型一维数组
     */
    public ArrayList  distanceKnodes (TreeNode root, int target, int k) {
        //构建图
        TreeNode cur = root;
        Map<Integer, List<Integer>> graph = new HashMap<>();
        //BFS,二叉树的层序遍历
        Queue<TreeNode> q = new LinkedList<>();
        q.add(cur);
        graph.put(cur.val, new ArrayList<>());
        while (!q.isEmpty()) {
            TreeNode pop = q.poll();

            if (pop.left != null) {
                q.add(pop.left);
                graph.get(pop.val).add(pop.left.val);

                graph.put(pop.left.val, new ArrayList<>());
                graph.get(pop.left.val).add(pop.val);
            }

            if (pop.right != null) {
                q.add(pop.right);
                graph.get(pop.val).add(pop.right.val);
                graph.put(pop.right.val, new ArrayList<>());
                graph.get(pop.right.val).add(pop.val);
            }
        }


       //图的BFS
        Queue<Integer> queue = new LinkedList<>();
        queue.add(target);
        Set<Integer> visited = new HashSet<>();
        visited.add(target);
        while (k >= 0) {
            k--;


            int size = queue.size();
            for (int i = 0; i < size ; i++) {
                int pop = queue.poll();

                for (Integer next : graph.get(pop)) {
                    if (visited.contains(next)) continue;
                    queue.add(next);
                    visited.add(next);
                }
            }


            if ( k == 0) break;
        }


        ArrayList<Integer> ans = new ArrayList <>();
        int size = queue.size();
        for (int i = 0; i < size ; i++) {
           ans.add( queue.poll());
        }
        return ans;
    }
}

Go代码

package main

import . "nc_tools"

/*
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param root TreeNode类
 * @param target int整型
 * @param k int整型
 * @return int整型一维数组
 */
func distanceKnodes(root *TreeNode, target int, k int) []int {
	//BFS
	graph := map[int][]int{} //构件图

	//层序遍历二叉树
	q1 := []*TreeNode{}
	q1 = append(q1, root)
	graph[root.Val] = []int{}

	for len(q1) > 0 {
		size := len(q1)
		q1bak := []*TreeNode{}
		for i := 0; i < size; i++ {
			pop := q1[i]
			a := pop.Val
			if pop.Left != nil {
				q1bak = append(q1bak, pop.Left)
				b := pop.Left.Val
				graph[a] = append(graph[a], b)
				graph[b] = []int{a}
			}

			if pop.Right != nil {
				q1bak = append(q1bak, pop.Right)
				c := pop.Right.Val
				graph[a] = append(graph[a], c)
				graph[c] = []int{a}
			}
		}

		q1 = q1bak
	}

	//图的BFS
	q := []int{target}
	visited := map[int]bool{}
	visited[target] = true
	for k >= 0 {
		k--
		size := len(q)
		qbak := []int{}
		for i := 0; i < size; i++ {
			pop := q[i]

			nexts := graph[pop]
			for _, next := range nexts {
				_, ok := visited[next]
				if ok {
					continue
				}

				qbak = append(qbak, next)
				visited[next] = true
			}
		}

		q = qbak
		if k == 0 {
			break
		}
	}

	return q
}

PHP代码

<?php

/*class TreeNode{
    var $val;
    var $left = NULL;
    var $right = NULL;
    function __construct($val){
        $this->val = $val;
    }
}*/

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param root TreeNode类 
 * @param target int整型 
 * @param k int整型 
 * @return int整型一维数组
 */
function distanceKnodes( $root ,  $target ,  $k )
{
      //BFS
    $graph = array(); //构建图
    //二叉树的层序遍历
    $q1 = [$root];
    $graph[$root->val] = array();
    while (count($q1) >0){
        $q1bak=array();
        $size = count($q1);
        for($i=0;$i<$size;$i++){
            $pop = $q1[$i];
            $a = $pop->val;

            if($pop->left!=null){
                $q1bak[count($q1bak)] = $pop->left;
                $b = $pop->left->val;
                $graph[$a][count($graph[$a])] = $b;
                $graph[$b]=[$a];
            }

            if($pop->right!=null){
                $q1bak[count($q1bak)] = $pop->right;
                $c = $pop->right->val;
                $graph[$a][count($graph[$a])] = $c;
                $graph[$c]=[$a];
            }
        }

        $q1=$q1bak;
    }

    //图的BFS
    $q = [$target];
    $visited = [$target=>$target];
    while ($k>=0){
        $k--;
        $size = count($q);
        $qbak = array();

        for($i=0;$i<$size;$i++){
            $nexts = $graph[$q[$i]];

            foreach ($nexts as $next){
                if(isset($visited[$next])) continue;

                $qbak[count($qbak)]  =$next;
                $visited[$next] = $next;
            }
        }
        $q = $qbak;
        if($k ==0) break;
    }

    return $q;
}

C++ 代码

/**
 * struct TreeNode {
 *  int val;
 *  struct TreeNode *left;
 *  struct TreeNode *right;
 *  TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param root TreeNode类
     * @param target int整型
     * @param k int整型
     * @return int整型vector
     */
    vector<int> distanceKnodes(TreeNode* root, int target, int k) {
        //BFS

        //二叉树层序遍历
        vector<TreeNode> q1;
        std::map<int, vector<int>> graph;
        q1.push_back(*root);
        graph[root->val] = vector<int>();


        while (q1.size() > 0) {
            vector<TreeNode> q1bak;
            int size = q1.size();
            for (int i = 0; i < size; i++) {
                TreeNode pop = q1[i];
                int a = pop.val;

                if (pop.left != nullptr) {
                    q1bak.push_back(*pop.left);
                    int b = pop.left->val;
                    graph[a].push_back(b);
                    graph[b] = vector<int>();
                    graph[b].push_back(a);
                }

                if (pop.right != nullptr) {
                    q1bak.push_back(*pop.right);
                    int c = pop.right->val;
                    graph[a].push_back(c);
                    graph[c] = vector<int>();
                    graph[c].push_back(a);
                }
            }
            q1 = q1bak;
        }

        //图的BFS
        vector<int> q = {target};
        std::map<int, bool> visited;
        visited[target] = true;

        while (k >= 0) {
            k--;
            int size = q.size();
            vector<int> qbak;
            for (int i = 0; i < size; i++) {
                vector<int> nexts = graph[q[i]];

                for (int j = 0; j < nexts.size(); j++) {
                    int next = nexts[j];
                    if (visited.count(next) == 0) {
                        visited[next] = true;
                        qbak.push_back(next);
                    }
                }
            }
            q = qbak;
            if (k == 0) break;

        }
        return q;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赵长辉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值