Java資料結構:求二叉樹一個結點的父母結點
阿新 • • 發佈:2018-12-31
類似於二叉樹的遍歷,引用結點的左右結點與待查結點進行比較
public BinaryNode<T> getParent(BinaryNode<T> node) { if (root==null || node==null || node==root) return null; return getParent(root, node); } //在以p為根的子樹中查詢並返回node結點的父母結點 public BinaryNode<T> getParent(BinaryNode<T> p, BinaryNode<T> node) { if (p==null) return null; if (p.left==node || p.right==node) return p; BinaryNode<T> find = getParent(p.left, node); if (find==null) find = getParent(p.right, node); return find; }