建站資源低價刷粉網(wǎng)站推廣
與其明天開始,不如現(xiàn)在行動!
文章目錄
- 1 后繼節(jié)點
- 1.1 解題思路
- 1.2 代碼實現(xiàn)
- 💎總結(jié)
1 后繼節(jié)點
1.1 解題思路
二叉樹節(jié)點結(jié)構(gòu)定義如下:
public static class Node {
public int cal;
public Node left;
public Node right;
public Node parent;
}
給你二叉樹中的某個節(jié)點,返回該節(jié)點的后繼節(jié)點
后繼節(jié)點就是二叉樹中序遍歷,這個節(jié)點的下一個節(jié)點
思路
- 如果該節(jié)點有右子樹,那么后繼節(jié)點就是右樹的最左節(jié)點
- 如果該節(jié)點沒有右子樹
- 如果該節(jié)點是父節(jié)點的左節(jié)點,此時父節(jié)點就是后繼節(jié)點
- 如果該節(jié)點是父節(jié)點的右節(jié)點,向上尋找
- 這個節(jié)點在頂部節(jié)點的右樹上,此時返回的是空
- 如果這個節(jié)點在某個節(jié)點的左數(shù)上,返回此時的節(jié)點
1.2 代碼實現(xiàn)
public class SuccessorNode {public static class Node {public int val;public Node left;public Node right;public Node parent;public Node(int val) {this.val = val;}}public static Node getSuccessorNode(Node node) {if (node == null) {return node;}if (node.right != null) {return getLeftMost(node.right);}else{Node cur = node;Node parent = node.parent;while (parent != null && parent.left != node) {cur = parent;parent = cur.parent;}return parent;}}private static Node getLeftMost(Node node) {Node cur = node;if (cur.left != null) {cur = cur.left;}return cur;}// 測試public static void main(String[] args) {Node n1 = new Node(1);Node n2 = new Node(2);Node n3 = new Node(3);Node n4 = new Node(4);Node n5 = new Node(5);Node n6 = new Node(6);Node n7 = new Node(7);n1.left = n2;n1.right = n3;n2.left = n4;n2.right = n5;n2.parent = n1;n3.left = n6;n3.right = n7;n3.parent = n1;n4.parent = n2;n5.parent = n2;n6.parent = n3;n7.parent = n3;System.out.println(getSuccessorNode(n6).val);}
}
💎總結(jié)
本文中若是有出現(xiàn)的錯誤請在評論區(qū)或者私信指出,我再進行改正優(yōu)化,如果文章對你有所幫助,請給博主一個寶貴的三連,感謝大家😘!!!