剑指offer(62)二叉树第k个节点

本文详细介绍了两种寻找二叉树中序遍历第K个节点的方法:非递归和递归方式。非递归方法使用栈进行节点存储,通过循环遍历左子树并计数找到目标节点;递归方法通过递归左右子树,并在访问根节点时检查计数是否等于K来实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一  非递归方式

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
import java.util.Stack;
public class Solution {
    TreeNode KthNode(TreeNode pRoot, int k)
    {
        if(pRoot == null || k <= 0){
            return null;
        }
        Stack<TreeNode> stack = new Stack<TreeNode>();
        int index = 0;
        while(pRoot != null || !stack.isEmpty()){
            if(pRoot != null){
                stack.push(pRoot);
                pRoot = pRoot.left;
            }else{
                pRoot = stack.pop();
                index++;
                if(index == k){
                    return pRoot;
                }
                pRoot = pRoot.right;
            }
           
            
        }
        return null;
    }


}

 

二 递归方式

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    int index = 0;
    TreeNode KthNode(TreeNode root, int k)
    {
        if(root != null){
            TreeNode node = KthNode(root.left, k);//左边遍历
            if(node != null){
                return node;
            }
            index++;
            if(index == k){
                return root;
            }
            node = KthNode(root.right, k);//右边遍历
            if(node != null){
                return node;
            }
            
        }
        return null;
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值