给定一个二叉树,从左到右,找出第 k 个叶子节点 [# 65]

问题:

给定一个二叉树,从左到右,找出第 k 个叶子节点。比如


图中二叉树的第 3 个叶子节点(从左到右)是 11.

分析:

因为顺序是从左往右数,所以,对于一个节点下的两个叶子节点来讲(比如 6 下面有两个叶子节点 5 和 11),我们要确保先遍历最左边一个,然后再遍历右边一个。这样,其实,在中序遍历,前序遍历和后序遍历中,都能保证左边叶子节点比右边叶子节点先被遍历。我们只需要对每一个遍历的节点进行检查,看是否是叶子节点,是,则把个数+1. 代码如下:

public class NthLeaf {
	
	static int k = 0;

	// get the nth leaf by using preorder traversal
	public void getNthleve(Node root, int n) {
		
		if (root == null) return;
		
		if (root.rightChild == null && root.leftChild == null) {
			k++;
			if (k == n) {
				System.out.print(root.toString());
			}
		}

		getNthleve(root.leftChild, n);
		getNthleve(root.rightChild, n);
	}
	
	public static void main(String[] args) {
		 Node a = new Node(2);
	     Node b = new Node(7);
	     Node c = new Node(5);
	     Node d = new Node(2);
	     Node e = new Node(6);
	     Node f = new Node(9);
	     Node g = new Node(5);
	     Node h = new Node(11);
	     Node i = new Node(4);
	     
	     a.leftChild = b;
	     a.rightChild = c;
	     b.leftChild = d;
	     b.rightChild = e;
	     c.rightChild = f;
	     e.leftChild = g;
	     e.rightChild = h;
	     f.rightChild = i;
	     
	     new NthLeaf().getNthleve(a, 3);		
	}
}

class Node {
    Node leftChild = null;
    Node rightChild = null;
    int value;

    Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return value + "";
    }
}

转载请注明出处:http://blog.csdn.net/beiyeqingteng
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值