新手算法學習之路----二叉樹(在一個二叉查找樹中插入一個節點)


題目:給定一棵二叉查找樹和一個新的樹節點,將節點插入到樹中。

          你需要保證該樹仍然是一棵二叉查找樹。

給出如下一棵二叉查找樹,在插入節點6之后這棵二叉查找樹可以是這樣的:

  2             2
 / \           / \
1   4   -->   1   4
   /             / \ 
  3             3   6
需要搞清楚定義:二叉排序樹或者是一棵空樹;或者是具有下列性質的二叉樹:
(1)若左子樹不空,則左子樹上所有結點的值均小於它的根結點的值;
(2)若右子樹不空,則右子樹上所有結點的值均大於它的根結點的值;
(3)左、右子樹也分別為二叉排序樹;

Java代碼:
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of the binary search tree.
     * @param node: insert this node into the binary search tree
     * @return: The root of the new binary search tree.
     */
    public TreeNode insertNode(TreeNode root, TreeNode node) {
        // write your code here
        if(root==null){
            return node;
        }
        if(root.val>node.val){                       //這個樹里面沒有重復的數,所以無需考慮root.val == node.val的情況
            root.left = insertNode(root.left, node);  //待插入值肯定在左右子樹的葉子幾點上面
        }else{
            root.right = insertNode(root.right,node);
        }
        return root;//最后返回的root值為根節點,每次遞歸后就要返回當前的root值,以備上一層使用,最后返回整個樹的根節點
    }
    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM