求二叉树根节点到指定节点的路径

article/2025/9/20 2:21:53

算法 求二叉树根节点到指定节点的路径

@author:Jingdai
@date:2020.11.05

题目描述

给你一个棵二叉树,再给你一个指定的节点,求根节点到指定节点的路径。

在这里插入图片描述

如图,比如让你求到 4 节点的路径,则应该返回的路径为 [0, 1, 4]

思路

利用二叉树的先序遍历,寻找指定的节点,同时用一个栈 stack 记录遍历到的节点,当找到需要的节点后立即返回结果。但是这样有一个问题,就是在遍历中 stack 记录的路径中包含一些其他的节点,比如要求上图中到 4 节点的路径,则遍历到 4 节点时,stack 中的路径就为 [0, 1, 3, 5, 6, 7, 8, 4],而需要的路径为 [0, 1, 4] ,中间多了许多不需要的节点。

为了去掉 stack 中不需要的节点,需要在递归查找过程中进行回溯,pop 这些不需要的节点。先序遍历查找是先看根节点是否满足要求、若不满足要求再去左子树和右子树中去查找,如果右子树还是找不到,说明该节点不在路径中,需要弹出该节点。

综上,代码片段如下:

public static boolean getPathToTarget(TreeNode node, TreeNode target, LinkedList<TreeNode> path) {if (node == null) return false;path.push(node);if (node == target)return true;// find in left treeif (getPathToTarget(node.left, target, path)) return true; // find in right treeif (getPathToTarget(node.right, target, path))return true;// this node is not in the path of target// cause leftchild rightchild and itself do not have target nodepath.pop();return false;
}

为了测试整个代码的正确性,使用LeetCode 定义的 TreeNode 来建立树,然后进行测试,完整的代码如下。

代码

import java.util.*;public class Solution {public static void main(String[] args) {// create treeTreeNode root = new TreeNode(0);TreeNode node1 = new TreeNode(1);TreeNode node2 = new TreeNode(2);TreeNode node3 = new TreeNode(3);TreeNode node4 = new TreeNode(4);TreeNode node5 = new TreeNode(5);TreeNode node6 = new TreeNode(6);TreeNode node7 = new TreeNode(7);TreeNode node8 = new TreeNode(8);root.left = node1;root.right = node2;node1.left = node3;node1.right = node4;node3.left = node5;node3.right = node6;node6.left = node7;node6.right = node8;// testLinkedList<TreeNode> path = new LinkedList<>();// get the path to node4boolean hasPath = getPathToTarget(root, node4, path);if (hasPath) {for (TreeNode node : path) {System.out.print(node.val + " ");}}System.out.println();System.out.println("============");path.clear();// get the path to nonexistent nodehasPath = getPathToTarget(root, new TreeNode(9), path);if (hasPath) {for (TreeNode node : path) {System.out.print(node.val + " ");}}}public static boolean getPathToTarget(TreeNode node, TreeNode target, LinkedList<TreeNode> path) {if (node == null) return false;path.push(node);if (node == target)return true;// find in left treeif (getPathToTarget(node.left, target, path)) return true; // find in right treeif (getPathToTarget(node.right, target, path))return true;// this node is not in the path of target// cause leftchild rightchild and itself do not have target nodepath.pop();return false;}
}class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) { val = x; }
}

http://chatgpt.dhexx.cn/article/2aCc5gKI.shtml

相关文章

二叉树节点和度的关系及特点

写在前边的话&#xff1a;你的支持是我写作的动力&#xff0c;有帮助到你的话麻烦点赞加收藏呦。感激不尽&#xff01;如有错误也请留言指正 目录 一、完全二叉树 节点总数的特点 二、二叉树 度的特点 1.n0与n2的关系 2.节点总数和度的关系 三、例题 例题一 例题二 例题三 一…

二叉树的节点

1、前序&#xff1a;根结点第一个访问&#xff0c;然后访问左、右孩子&#xff1b; 后序&#xff1a;根结点最后访问&#xff0c;开始先访问左、右孩子&#xff1b; 中序&#xff1a;根结点第二个访问&#xff0c;最先访问左孩子&#xff0c;最后访问右孩子 前序序列&#x…

求二叉树的节点个数

如果是空树&#xff0c;则结点个数为0&#xff0c;递归结束 否则结点个数为左子树的结点个数右子树的结点个数1 【算法描述】 int NodeCount(BiTree T) {if (T NULL)return 0; // 如果是空树&#xff0c;则结点个数为0&#xff0c;递归结束elsereturn NodeCount(T->lchild…

数据结构-第五章 二叉树

一、树 1.树的概念 树是一种非线性的数据结构&#xff0c;是由n个结点组成的一个集合。每一棵树都可以被分解为根节点和n棵子树构成(n>0) 根节点(Root)&#xff1a;没有父结点的结点称为根节点&#xff0c;如A 父结点&#xff1a;含有子结点的结点&#xff0c;如A是B的父…

零基础学二叉树

目录 二叉树的定义&#xff1a; 二叉树的应用&#xff1a; 认识二叉树&#xff1a; 二叉树的基本形式&#xff1a; 二叉树的节点&#xff1a; 二叉树的高度和深度&#xff1a; 二叉树的子树&#xff1a; 二叉树的度&#xff1a; 满二叉树&#xff1a; 完全二叉树&…

npm 升级

npm 版本升级 mac版本 npm install -g npm1.网上有看到别的同学碰到升级报错的情况&#xff1a;可以试试用管理员身份安装&#xff1a; sudo npm install -g npm windows版本 npm install -g npm2.安装完成之后&#xff0c;输入npm -v检查是否升级成功&#xff0c;我是从6.…

npm 升级依赖包

首先安装升级插件 npm-check-updates $ npm install -g npm-check-updates # 或者 $ cnpm install -g npm-check-updates ncu 是 npm-check-updates 的缩写命令 输入ncu命令&#xff0c;可以看到需要升级安装包 # 查看更新ncu 可以看到有好几个包要更新 # 查看所有ncu命令…

npm升级自身版本

查看版本&#xff1a;npm -v 查看版本详情&#xff1a;npm version 用命令npm view npm version&#xff0c;运行后会输出到目前为止npm的所有版本&#xff0c;如图&#xff1a; 升级为特定的版本&#xff0c;命令:npm -g install npm4.0.2,运行后并检验版本如图&#xff1a;…

npm 升级后,无法运行

更新npm npm install -g npm9.2.0问题&#xff1a;无法加载文件 D:\Program Files\nodejs\npm.ps1&#xff0c;因为在此系统上禁止运行脚本。 解决&#xff1a;依次输入如下命令 get-ExecutionPolicySet-ExecutionPolicy -Scope CurrentUserRemoteSignedget-ExecutionPolicy…

npm升级

啥时候升级&#xff1f; 在使用npm安装依赖包&#xff0c;终端出现以下提示 New major version of npm available! 6.13.4 -> 8.5.5 Changelog: https://github.com/npm/cli/releases/tag/v8.5.5 Run npm install -g npm to update! 如何升级 npm install npm -g升级报…

npm升级导致npm报错

文章目录 问题解决其他 问题 事情起因在于&#xff0c;我在执行npm init -y的时候&#xff0c;提示我可以升级 好家伙&#xff0c;脑子一时不清醒&#xff0c;我就执行了。以前看到都没想过要执行&#xff0c;今天不知道怎么了&#xff0c;也许是早饭吃多了撑的 : ) 执行完之…

npm 升级遇到的问题

问题&#xff1a;在VUE项目中&#xff0c;当前的npm版本有点低&#xff0c;想对npm进行升级&#xff0c;将npm从6.14.13的版本升级到8.0.0版本&#xff0c;运行npm install -g npm8.0.0报错 解决方法&#xff1a; 找到node文件夹下面的npm.cmd&#xff0c;将它重命名为npmx.cm…

npm 升级node.js

升级NPM 到最新 查看npm 版本&#xff1a; npm -v 更新到最新版本&#xff1a; npm install npmlatest -g 升级Node.js 从node官网下载最新node.js 安装包覆盖原理的node.js 最新node.js 下载 winr cmd 输入 where node 查看原来node 安装路径 安装成功后查看node 版本

如何升级npm 和 安装nvm 及 升级node.js

1.NPM如何升级&#xff1f; 1.1.可以使用NPM自带的命令进行升级&#xff1a; npm install -g npm 注&#xff1a;这个命令会安装最新的&#xff0c;安装到全局。 2.查看NPM版本 npm -v 注&#xff1a;要是版本过低&#xff0c;可使用上面所说命令进行升级。 3.怎么把node.js升…

算法优化(1):基础知识-凸集,单峰函数,拟凸函数与凸函数,函数凹凸性定义

本文笔记介绍我最近学习的算法优化的基础知识&#xff0c;有&#xff1a; 最优化问题的一般形式约束问题的分类及形式优化问题的分类单峰函数&#xff08;Unimodal function&#xff09;的定义拟凸函数&#xff08;Quasiconvex function&#xff09;的定义凸集&#xff08;conv…

deep_learning_凹凸函数

什么是凸函数及如何判断一个函数是否是凸函数 t元j 一、什么是凸函数 对于一元函数f(xf(x)&#xff0c;如果对于任意tϵ[0,1]tϵ[0,1]均满足&#xff1a;f(tx1(1−t)x2)≤tf(x1)(1−t)f(x2)f(tx1(1−t)x2)≤tf(x1)(1−t)f(x2)&#xff0c;则称f(x)f(x)为凸函数(convex function…

德.摩根定律及其理解

德.摩根定律的定义如下&#xff1a; 文字描述如下&#xff1a; 使用对偶性可以很方便的记忆和使用这个定律。. 我们知道如下关系呈现对偶关系&#xff0c;可以认为是“非”的关系&#xff1a; 那么将 利用对偶关系对应改写可以得到&#xff1a; .那么可以对应得到&#xff1a;…