二叉树查找x的祖先

package edu.lnu.fang.BiTree;

import java.util.Iterator;
import java.util.Stack;

import edu.lnu.fang.BiTree.BinTreeTra.Node;

public class SearchAncestor {
    static void printS(Stack S) {
        Iterator<Node> iterator = S.iterator();
        while (iterator.hasNext()) {
            System.out.print(iterator.next().data + " ");
        }
    }
/** * 寻找值为x(假设只有一个值为x的节点)的节点的所有祖先 * @param root * @param x */
    static void search(Node root, int x) {
        Stack<Node> S = new Stack<Node>();
        Node p = root;
        Node r = null;

        while (p != null || S.size() > 0) {
            if (p != null) {
                S.add(p);
                p = p.leftChild;

            } else {
                p = S.peek();
                if (p.rightChild != null && p.rightChild != r) {
                    p = p.rightChild;
                    S.add(p);
                    p = p.leftChild;
                } else {
                    p = S.pop();
                    if(p.data==x){
                        printS(S);
                        return;
                    }
                    //BinTreeTra.printNode(p);
                    r = p;
                    p = null;
                }
            }
        }
    }

    public static void main(String[] args) {
        Node root = BinTreeTra.init();
        search(root,16);

    }
}
    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/fangchao3652/article/details/53456456
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞