劍指offer_二叉樹的下一個結點

問題

例子

思路

  • 方法1
    在這裏插入圖片描述

  • 方法2
    1: 如果該結點有右子樹,則返回右子樹最深的左子樹
    在這裏插入圖片描述
    2:如果該結點沒有右子樹,不斷向上找該結點的父結點。
    2.1:如果存在某個父節點,是其父節點的左子樹,則返回其父節點
    在這裏插入圖片描述
    2.2:如果不存在某個父節點,是其父節點的左子樹,則返回null
    在這裏插入圖片描述

代碼

//方法1
import java.util.*;
public class Solution {
    private TreeLinkNode res = null;

    public TreeLinkNode GetNext(TreeLinkNode pNode)
    {
        TreeLinkNode node = pNode;
        while(node.next!=null) {
            node = node.next;
        }
        TreeLinkNode root=node;
        midOrder(root,pNode);
        return res;
    }
    public void midOrder(TreeLinkNode root, TreeLinkNode node) {
        if(root==null) return;

        if(root.left!=null) midOrder(root.left,node);
        if(root!=node && node.val<=root.val) {
            //只找第一個滿足條件的,此時res爲null
            if(res==null) {
                res=root;
            }
            return;


        }
        if(root.right!=null) midOrder(root.right,node);
    }
}
//方法2
public class Solution {
    public TreeLinkNode GetNext(TreeLinkNode pNode)
    {
        if(pNode==null) return null;
        if(pNode.right!=null) {
            TreeLinkNode node = pNode.right;
            while(node.left!=null) {
                node=node.left;
            }
            return node;
        }
        while(pNode.next!=null) {
            if(pNode.next.left==pNode) return pNode.next;
            pNode = pNode.next;
        }
        return null;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章